understanding insertion sort algorithm code example

Example 1: insertion sort

def insertionSort(arr): 
    for i in range(1, len(arr)): 
        key = arr[i] 
        j = i-1
        while j >= 0 and key < arr[j] : 
                arr[j + 1] = arr[j] 
                j -= 1
        arr[j + 1] = key

Example 2: insertion sort

//insertion sort
#include <iostream>

using namespace std;
void insertion_sort(int arr[],int n)
{
    int value,index;
    for(int i=1;i<n;i++)
    {
        value=arr[i];
        index=i;
        while(index>0&&arr[index-1]>value)
        {
            arr[index]=arr[index-1];
            index--;

        }
        arr[index]=value;
    }
}
void display(int arr[],int n)
{
    for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<" ";
    }
    cout<<endl;
}

int main()
{
    int n;
    cout<<"enter the size of the array:"<<endl;
    cin>>n;
    int array_of_numbers[n];
    cout<<"enter the elements of the array:"<<endl;
    for(int i=0;i<n;i++)
    {
        cin>>array_of_numbers[i];
    }
    cout<<"array before sorting:"<<endl;
    display(array_of_numbers,n);
    insertion_sort(array_of_numbers,n);
    cout<<"array after sorting is:"<<endl;
    display(array_of_numbers,n);

    return 0;
}

Tags:

Java Example