Sorting Review
Sorting Review
REVIEW
QUADRATIC – executes in n2 time
IN-PLACE – sorts without using extra space outside the container itself
Worst = O(n2)
Average = O(n2)
Best = O(n2)
Best case is O(n) because
Space = O(1) there is an optimization
technique you can use in
the algorithm to check if
the array is already
Insertion sort: QUADRATIC, IN-PLACE sorted
after 2nd pass
There is a sorted, and an unsorted region. Initially, sorted region has only one This means for a
element (the first element). sorted array,
Bubble sort will
Grab the first element from the unsorted region and insert it into its correct place execute in O(n)
within the sorted region. Repeat until there are no more elements in unsorted time
region.
Initial Array
Worst = O(n2)
Average = O(n2)
after 1st pass Grab first element in Best = O(n)
after 3rd pass
unsorted region (3) and
place where it belongs Space = O(1)
(before 7) in sorted
after 2nd pass region
Shell sort
after 3rd pass Shell sort is a special variant of insertion sort but with O(n3/2) performance :D
Sorts many smaller subarrays using insertion sort before sorting entire array.
Initial Array
after 4th pass Gap = n /2 = 4 Compare and swap!
Worst = O(n*log(n))
Average = O(n*log(n))
- mergeSort takes O(log(n)) time and merge takes O(n) time Best = O(n*log(n))
so together, they take O(n*log(n)) time Space = O(n)
up down
up down
down up