insertion sort explanation 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: program for insertion sort

# another method similar to insertion sort

def insertionSort(arr):
    for i in range(1, len(arr)):
        k = i
        for j in range(i-1, -1, -1):
            if arr[k] < arr[j]:  # if the key element is smaller than elements before it
                temp = arr[k]  # swapping the two numbers
                arr[k] = arr[j]
                arr[j] = temp

                k = j  # assigning the current index of key value to k
        

arr = [5, 2, 9, 1, 10, 19, 12, 11, 18, 13, 23, 20, 27, 28, 24, -2]

print("original array \n", arr)
insertionSort(arr)
print("\nSorted array \n", arr)

Example 3: insertion sort

// Por ter uma complexidade alta,
// não é recomendado para um conjunto de dados muito grande.
// Complexidade: O(n²) / O(n**2) / O(n^2)
// @see https://www.youtube.com/watch?v=TZRWRjq2CAg
// @see https://www.cs.usfca.edu/~galles/visualization/ComparisonSort.html

function insertionSort(vetor) {
    let current;
    for (let i = 1; i < vetor.length; i += 1) {
        let j = i - 1;
        current = vetor[i];
        while (j >= 0 && current < vetor[j]) {
            vetor[j + 1] = vetor[j];
            j--;
        }
        vetor[j + 1] = current;
    }
    return vetor;
}

insertionSort([1, 2, 5, 8, 3, 4])

Example 4: 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;  
}

Tags: