Data Structures and Algorithms
Primary version
Primary version
  • Data Structures and Algorithms
  • Algorithms Analysis
    • Measuring Resource Consumption
    • Growth Rates
    • Asymptotic Notation
    • Analysis of Linear Search
    • Analysis of Binary Search
    • How to do an analysis in 5 steps
  • Recursion
    • Writing a recursive function
    • How do recursive functions work?
    • Analysis of a Recursive Function
    • Drawbacks of Recursion and Caution
  • Lists
    • Implementation
    • Linked List
      • Concepts
      • Implementation - List and Nodes
      • Implementation - push_front(), pop_front()
      • Implementation - Iterators
      • Modification - Sentinel Nodes
  • Stacks and Queues
    • Stack Implementation
    • Queue Implementation
  • Table
    • A Simple Implementation
    • Hash Tables
      • Bucketing
      • Chaining
      • Linear Probing
  • Sorting
    • Simple Sorts
      • Bubble Sort
      • Insertion Sort
      • Selection Sort
    • Merge Sort
    • Quick Sort
    • Heap and Heap Sort
      • Priority Queues using Binary Heaps
      • Heapify and Heap Sort
  • Trees
    • Binary Trees
    • Binary Search Trees
    • BST Implemenation
    • Iterative Methods
    • Recursive Methods
  • AVL Trees
  • Red Black Trees
  • 2-3 Trees
  • Graphs
  • Introduction to Computational Theory
  • Appendix: Markdown
  • Appendix: Mathematics Review
Powered by GitBook
On this page
  • Introduction
  • Algorithm
  • Animation
  • C/C++ Implementation
  1. Sorting
  2. Simple Sorts

Insertion Sort

PreviousBubble SortNextSelection Sort

Last updated 6 years ago

Introduction

Insertion sort is called insertion sort because the algorithm repeated inserts a value into an array that is already sorted. It essentially chops the array into two pieces. The first piece is sorted, the second is not. We repeatedly take a number from the second piece and insert it into the already sorted first piece of the array.

Algorithm

  1. start with second variable.

  2. put number into a temporary variable. This makes it possible to move items into the spot the number use to occupy. This spot is now considered to be an empty spot in the sorted portion of the array

  3. if number in temporary can go into empty spot, put it in

  4. otherwise move last item in the part into empty spot

  5. repeat steps 3 to 4 until item is temp is placed into the first part of the array

  6. repeat for every number in the second part of the array until all numbers are placed

Animation

C/C++ Implementation

void insertionSort(int arr[],int size){
    int curr;
    int i, j;
    for(i=1;i<size;i++){
        curr=arr[i];
        for(j=i;j>0 && arr[j-1] > curr;j--){
            arr[j]=arr[j-1];
        }
        arr[j]=curr;
    }
}

Data Structure Animations using Processing.js by cathyatseneca