Sorting
Sorting
1
• How to use standard sorting methods
• How to implement these sorting algorithms:
• Selection sort
• Bubble sort
• Insertion sort
• Shell sort
• Merge sort
• Heap sort
• Quick sort
• Understand the performance of these algorithms
1. do
2. for each pair of adjacent array elements
3. if values are out of order
4. Exchange the values
5. while the array is not sorted
Bubble Sort Algorithm, Refined
1. do
2. Initialize exchanges to false
3. for each pair of adjacent array elements
4. if values are out of order
5. Exchange the values
6. Set exchanges to true
7. while exchanges
Analysis of Bubble Sort
• To make room:
• Hold nextPos value in a variable
• Shuffle elements to the right until gap at right place
Insertion Sort Example
Analysis of Insertion Sort
Overview:
• Split array into two halves
• Sort the left half (recursively)
• Sort the right half (recursively)
• Merge the two sorted halves
Merge Sort Algorithm (2)
Detailed algorithm:
• if tSize £ 1, return (no sorting required)
• set hSize to tSize / 2
• Allocate LTab of size hSize
• Allocate RTab of size tSize – hSize
• Copy elements 0 .. hSize – 1 to LTab
• Copy elements hSize .. tSize – 1 to RTab
• Sort LTab recursively
• Sort RTab recursively
• Merge LTab and RTab into a
Merge Sort Example
Merge Sort Analysis
• Splitting/copying n elements to subarrays: O(n)
• Merging back into original array: O(n)
• Recursive calls: 2, each of size n/2
• Their total non-recursive work: O(n)
• Next level: 4 calls, each of size n/4
• Non-recursive work again O(n)
• Size sequence: n, n/2, n/4, ..., 1
• Number of levels = log n
• Total work: O(n log n)
Heapsort
• Merge sort time is O(n log n)
• But requires (temporarily) n extra storage items
• Heapsort
• Works in place: no additional storage
• Offers same O(n log n) performance
• Idea (not quite in-place):
• Insert each element into a priority queue
• Repeatedly remove from priority queue to array
• Array slots go from 0 to n-1
Heapsort Picture
Heapsort Picture (2)
Algorithm for In-Place Heapsort