Part 5 Flashcards
What is the principle of divide and conquer?
A large problem should be broken down into several smaller problems
how does divide and conquer work when sorting a collection?
split into two collections, sort them, then somehow merge the two collections
What are the best, average and worst time complexities of insertion sort?
Best: O(n)
Average: O(n2)
Worst: O(n2)
What are the best, average, and worst time complexities of mergesort?
O(nlogn) for all
What are the best, average and worst time complexites of selection sort?
O(n2) for all
What is the difference between easy-split hard-merge and hard-split easy-merge?
ESHM: splitting into two lists is easy, work done in merging sorted sublists
HSEM: splitting is difficult - have to split into large half and small half sublists, but then once they’re sorted can just merge by appending the large list to the small one
Is insertion sort easy-split hard-merge, or hard-split easy-merge?
Easy split hard merge
How does insertion sort work?
Split list into two lists of size 1 and n-1
Sort the n-1 list
Insert the 1 into the correct position in the n-1 list
Is mergesort easy split hard merge or hard split easy merge?
easy split hard merge
How does mergesort work?
Split list into two equal sized lists
sort them by mergesort
iterate over both lists at the same time
add smaller of the two current items from the two lists to the result array
if one array is empty, append the other to the end of the results list
Is selection sort easy split hard merge or hard split easy merge?
hard split easy merge
how does selection sort work?
Swap the pos+1th number of the list with the smallest number from the rest of the list, until the end of the list has been reached
recursive
is quicksort easy split hard merge or hard split easy merge?
hard split easy merge
How does quicksort work?
Approximate the median of the list - the pivot. pivot must not be largest number in list so dont count duplicates
split list into two lists where l1 are all <= the pivot and l2 are all > pivot
to find the split point:
using two cursors starting from left and right
left cursor is incremented until an item > the pivot is found
right is decremented until item <= pivot is found
swap item
once cursors have crossed over found the split point
all items left of the cursor are less than the pivot and all on the right are greater
then sort the subarrays using quicksort
What is the best, average and worst time complexity of Quicksort?
Best: O(nlogn)
Average: O(nlogn)
Worst: O(n2)