Sorting B Ramamurthy 1192022 BR 1 Introduction z
Sorting B. Ramamurthy 1/19/2022 BR 1
Introduction z The problem of sorting an initially unsorted collection of keys to produce an ordered collection is one of the richest in computer science. z The richness derives from the fact that there a number of ways of solving the sorting problem. z It is a fascinating operation that provides a model for investigating many problem in Computer Science. 1/19/2022 BR 2
Topics for Discussion z. Sorting Basics z. Priority queue methods z. Insertion based methods z. Divide and conquer methods z. Summary 1/19/2022 BR 3
Comparison-based Sorting z Most sorting methods decide how to rearrange the keys into order by first comparing the values of the keys. These methods are called comparison-based methods. z Examples: Selection sort, insertion sort, merge sort, quick sort, heap sort, shell sort and tree sort. z The minimum average number of comparisons required to sort n keys using a comparisonbased sorting method is proportional to n log n. 1/19/2022 BR 4
Priority Queue Sorting Methods z. Using a tree : heap and delete, repeat. z. Selection sort: A realization of PQ method : unsorted sub-array of keys represents the PQ. 1/19/2022 BR 5
Selection Sort z. Number of comparisons : (n-1)+(n-2)…+2 +1 = n*(n-1)/2, or O(n 2 ) z. Number of exchanges : O(n) z. Therefore it is a O(n 2 ) algorithm. 1/19/2022 BR 6
Heap Sort z. The PQ part of the method is represented by a heap. z. This implies that every time PQ part has be re-heaped when a key is moved. This is because the PQ may loose its heap property when the root is removed. 1/19/2022 BR 7
Heap Sort Performance z Heaping takes : O(n) z. Remove key, move and sift up : O(n log n) z. Since the latter is dominant for a large n, z. Heap sort is an O(n log n) algorithm. 1/19/2022 BR 8
Insertion-based methods z. Main idea is to keep the keys in two list: sorted and unsorted. Sorting involves removing an element from the unsorted list and placing it in the sorted list in the right order. z. Especially useful when the complete list is not available apriori. z. Insertion sort (O(n ) ) and tree sort (O (n log n)) are examples. 1/19/2022 BR 9
Divide and Conquer methods z. Main idea: 1. Divide the initially given unsorted array into two sub-arrays 2. Sort the two subarrays 3. Combine the two sorted subarrays into the overall solution. z. Merge sort and Quick sort are examples of this method. Lets look at these with a sample list. 1/19/2022 BR 10
Example 1/19/2022 BR 11
Performance of Merge and Quick sorts z. Merge sort is an O(n log n) z. Quick sort in average case is O(n log n) 2 but is O(n ) in the worst case. 1/19/2022 BR 12
- Slides: 12