// 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