Insertion sort
1.Insertion sort
2.Procedures
3.Example code (Java)
public static void insertionSort(int[] listToSort) {
//Go up to the second to last element
for (int i = 0; i < listToSort.length - 1; i++) {
//Consider everything uptil the ith element sorted
//Bubble the element element outside the sorted sub-list to the right position
for (int j = i + 1; j > 0; j--) {
if (listToSort[j] < listToSort[j - 1]) {
swap(listToSort, j, j - 1);
} else {
//If no swap was performed the element has been moved to the right position so break out the loop
break;
}
}
print(listToSort);
}
}4.Complexity
5.Insertion sort v.s bubble sort
Last updated