Insertion Sort

Description: Takes an array of integers and the element count and sorts the list in ascending order.
Tested Platform: Visual Studio 64-bit, Windows 10
Language: C++
// Pass it an array of integers and the length of the array (its count)
void insertion_sort(int* theArray, int length) {

    // Loop index "i" from 1 to the end of the array.
    for (int i = 1; i < length; i++) {

        // Each iteration we get the current index value
        // Then set a variable equal to the preceeding index in the array.
        int value = theArray[i];
        int j = i - 1;

        // Loop backwards until we get to the beginning of the array 
        // or until our value is no longer less than the preceeding values.
        while ((j >= 0 ) && (value < theArray[j])) {
            theArray[j + 1] = theArray[j];
            theArray[j] = value;
            j--;
        }
    }
}

Posted: March 20, 2023

Return to the snippets listing