Professional Documents
Culture Documents
Previously
Sorting Defined; Sorting Algorithms for run-time complexity analysis
Algorithms for Sorting
Selection Sort and Insertion Sort: O(n2)
Shell Sort: O(n log2n)
Merge Sort and Heap Sort: O(n log n)
Quick Sort: O(n log n) ave case, O(n2) worst case
Other issue: B 0 2 0 4 5 0 0 8 9 0
What if there are duplicates? 1 2 3 4 5 6 7 8 9 10
Counting Sort
Variant of Bin Sort
Handles duplicate entries
A 8 5 8 4 5
B 0 0 0 0 0 0 0 0 0 0
1 2 3 4 5 6 7 8 9 10
Counting Sort
Variant of Bin Sort
Handles duplicate entries
A 8 5 8 4 5
B 0 0 0 1 2 0 0 2 0 0
1 2 3 4 5 6 7 8 9 10
Counting Sort
Variant of Bin Sort
Handles duplicate entries
By counting the number of
occurrences
A 4 5 5 8 8
B 0 0 0 1 2 0 0 2 0 0
1 2 3 4 5 6 7 8 9 10
Counting Sort
Try This!
Write algorithm for counting sort
What is the run-time complexity
of your solution?
Space complexity?
Can be used to sort mails by 0 1 2 3 4 5 6 7 8 9
zip codes?
Can be used to sort strings of
length < 20?
Can be used to sort real
numbers in general?
Sorting Issues
Does O(n log n) always beat O(n 2)?
Which should be considered: Best Case, Average Case or Worst Case?
Recursive vs Iterative
Recursive is normally easier to code (more intuitive most of the time)
Stack Overflow issue for recursive algorithms
Iterative normally runs faster
In-place sorting is usually faster, but normally requires more complex code
Memory/Secondary Storage Paging
Merge Sort needs contiguous array elements: potentially fewer page requests
Heap Sort needs array elements that are not contiguous (e.g., node k with its parent
node k/2 will be swapped)
How about Quick sort? Radix sort?
Closing
Many sorting algorithms available, most have several variants
For our course, the discussion of algorithms serves 2 main purposes:
Appreciation of different ways of accomplishing the same goal
Examples on analysis of run-time (and space) complexities, which is the
main basis for comparing different algorithms that solve the same problem