Ecs 36C Data Structures: Spring 2024 - Instructor Siena Saltzen
Ecs 36C Data Structures: Spring 2024 - Instructor Siena Saltzen
Data Structures
Spring 2024 - Instructor Siena Saltzen
Review Time
So we have the ability to sort with O(n lg n) speed, and search with O(lg n) speed.
That’s really good. But we still have some issues. What might those be?
Where are we gonna put that 7 billion element "world phone book" list in memory?
Finding that much contiguous available memory might be problematic. A data
structure that was more flexible, more dynamic, and much less dependent on
contiguous memory could be helpful. What kind of structure might that be?
Now that we’ve sorted our 7 billion element list in O(n lg n) time, what
do we do if we want to add one more element in the right place? How
about if we add that element to the end of the existing list and then
apply quicksort to the whole thing again?
What input causes quicksort to perform with its absolute worst time
complexity (i.e. O(n^2))*?
So if we’re doing 1 billion comparisons per second, we can quicksort the original
unsorted list in less than 4 minutes, according to what we have learned. But once
the list is sorted, if we want to add an element that belongs just before the current
last item in the list, that’ll take more than 1500 years?!
Isn’t it nice that you know something about algorithm analysis now? Let’s try
another approach...
Issue #2
How about we just insert the element in its appropriate place by searching the
sorted array until we find the right place, then make a space by moving all the
elements past that place one space toward the back, like one pass of insertion
sort. What’s the time complexity of insertion now? Using binary search, we
can find the insertion point in O(lg n) comparisons, but moving elements will
take O(n) movements. O(n) beats O(n^2), but...
Maybe we could speed up the insertion time even more. Before we
hinted at a linked list structure for flexibility. Can we do binary search
on a singly-linked list to get that O(lg n) time complexity?
This can all be done in place in the array that holds the heap, but it’s easier to see if
we draw the trees instead of the array. Once you see how it works with trees, make
sure you understand how it works in place in the array.
Heapsort
Now it’s sorted, but it’s largest to smallest (reading top to bottom, left to right). We
created a min heap, and we ended up with the sequence sorted from largest to
smallest. The same thing will happen when sorting in place in the array.
Heapsort