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)
How to merge 2 sorted lists (during merge sort?)
Grab the smallest element from the 2 lists and append to auxiliary array
What do you do when merging two sorted arrays and one of the two lists is already completed?
Copy over all the elements of the remaining list

What is time complexity of merge sort?
O(NlogN)
What is the base case to break out of merge sort recursion?
When the sublist only has 1 element (1 element list is already sorted)
Merge sort visualized

What can you do to preprocess a collection/list to make searching fasting?
Sort (e.g. binary search benefits from sorted list)
What is the defintion of an in-place sort?
One that uses O(1) space
What is the definition of a stable sort?
One where entries which ae equal appear in their original order