cs101-notes
  • CS 101 Notes
  • Big O Notation
  • Big O Cheat Sheet
  • Sorting
    • Summary
    • Bubble Sort
    • Selection Sort
    • Insertion Sort
    • Merge Sort
    • Quick Sort
  • Abstract Data Types
    • Linked List
    • Stack
    • Queue
    • Hash Maps
    • Minimum Ordered Heap
Powered by GitBook
On this page

Was this helpful?

  1. Sorting

Insertion Sort

PreviousSelection SortNextMerge Sort

Last updated 5 years ago

Was this helpful?

template <typename eType>
void insertionSort(vector<eType> arr, int size) {
  int j, temp;
  for (int i = 1; i < size; i++) {
    j = i;
    while (j > 0 && arr[j] < arr[j - 1]) {
      temp = arr[j];
      arr[j] = arr[j - 1];
      arr[j - 1] = temp;
      j--;
    }
  }
}
Insertion Sort Visualization