Sorting Algorithms Flashcards
Is quicksort stable?
No
Can quicksort be done in-place?
Yes
Can merge sort be done in-place?
No. It requires O(n) space for the auxiliary array. There is an in-place version?
Is merge sort stable?
Yes
Is insertion sort stable?
Yes
Can insertion sort be done in-place?
Yes.
Can selection sort be done in-place?
Yes
Is selection sort stable?
No
Is heap sort stable?
No
What’s the best-case running time of binary search?
O(1) - we get lucky and find the element right at the midpoint.
What’s the worst-case running time of binary search?
O(log n)
How to code selection sort? and time and cost?
O(n^2) time
O(1) space – in-place sort
How to code insertion sort and cost?
Worst case: O(n^2) - everything in reverse/descending order
Best case: O(n) - everything in order/ascending
Why is insertion sort quadratic O(n^2) when input is reverse order?
each time we insert an element into the sorted portion, we’ll need to swap it with each of the elements already in the sorted list to get it all the way to the start. That’s 1 swap the first time, 2 swaps the second time, 3 swaps the third time, and so on, up to n - 1n−1 swaps for the last item.
Pseudo-code for merge sort
if len(list) < 2: return list
sorted_first = mergesort(first_half)
sorted_second = mergesort(second_half)
return merge(sorted_first, sorted_second)