Complete-Preparation

πŸŽ‰ One-stop destination for all your technical interview Preparation πŸŽ‰

View the Project on GitHub

Insertion Sort Algorithm

Insertion Sort

Code

void insertionSort(vector<int>& a, int n)
{
    int i, j, key;
    for (i = 1; i < n; i++) {
        key = a[i];
        // move key to its correct position in sorted array
        j = i - 1;
        while (j >= 0 && a[j] > key) {
            a[j + 1] = a[j];
            j--;
        }
        a[j + 1] = key;
    }
}

Binary Insertion Sort

Code


int binarySearch(vector<int>& a, int key, int lo, int hi)
{
    if (lo >= hi)
        return (key > a[lo]) ? lo + 1 : lo;

    int mid = (lo + hi) / 2;

    if (key == a[mid]) return mid + 1;

    if (key > a[mid])
        return binarySearch(a, key, mid + 1, hi);
    return binarySearch(a, key, lo, mid - 1);
}

void binaryInsertionSort(vector<int>& a, int n)
{
    for (int i = 1; i < n; i++) {
        int key = a[i];
        int j = i - 1;

        int loc = binarySearch(a, key, 0, j);
        while (j >= loc) {
            a[j + 1] = a[j];
            j--;
        }
        a[j + 1] = key;
    }
}

Analysis

Uses

Reference


Recursive Insertion Sort

Code

void insertionSortRec(vector<int>& a, int n)
{
    if (n == 1) return;

    // sort first n-1 elements
    insertionSortRec(a, n - 1);

    // insert last element to its correct position
    int last = a[n - 1];
    int j = n - 2;
    while (j >= 0 && a[j] > last) {
        a[j + 1] = a[j];
        j--;
    }
    a[j + 1] = last;
}