insertion sort diagram code example

Example 1: insertion sort

#include <bits/stdc++.h>

using namespace std; 

void insertionSort(int arr[], int n)  
{  
    int i, temp, j;  
    for (i = 1; i < n; i++) 
    {  
        temp = arr[i];  
        j = i - 1;  

        while (j >= 0 && arr[j] > temp) 
        {  
            arr[j + 1] = arr[j];  
            j = j - 1;  
        }  
        arr[j + 1] = temp;  
    }  
}

int main()  
{  
    int arr[] = { 1,4,2,5,333,3,5,7777,4,4,3,22,1,4,3,666,4,6,8,999,4,3,5,32 };  
    int n = sizeof(arr) / sizeof(arr[0]);  

    insertionSort(arr, n);  

    for(int i = 0; i < n; i++){
        cout << arr[i] << " ";
    }

    return 0;  
}

Example 2: insertion sort

function insertionSortRicorsivo(array A, int n)
     if n>1
        insertionSortRicorsivo(A,n-1)
        value ← A[n-1]
        j ← n-2
        while j >= 0 and A[j] > value 
         do A[j + 1] ← A[j]
            j ← j-1
        A[j+1] ← value

Tags:

Misc Example