Array Sorting
Ways to put an array in order, from quadratic to optimal
Pick a sorting algorithm and watch it rearrange the array one comparison at a time. Selection and insertion sort are simple but take quadratic time. On the other hand, merge sort, quicksort, and heapsort use divide and conquer, randomness, and a heap to reach
Selection Sort¶
Each pass scans the unsorted suffix for its minimum and swaps it into position . The scan always runs to the end, no matter what it finds, so every input costs the same:
Best Case:
Average Case:
Worst Case:
Insertion Sort¶
Each pass takes and shifts it left past every larger element in the sorted prefix . Every shift fixes exactly one inversion, a pair with and , so the cost depends on how out of order the input is.
Best Case:
In the best case the array is already sorted, so each element is compared once and never moves:
Worst Case:
In the worst case the array is reversed, so element is shifted past all elements before it:
Average Case:
On average, each of the pairs is inverted with probability , so the expected number of shifts is