1 Heapsort, Mergesort, and Quicksort Sections 7.5 to 7.7.

Slides:



Advertisements
Similar presentations
Chapter 9 continued: Quicksort
Advertisements

Quick Sort, Shell Sort, Counting Sort, Radix Sort AND Bucket Sort
Chapter 4: Divide and Conquer Master Theorem, Mergesort, Quicksort, Binary Search, Binary Trees The Design and Analysis of Algorithms.
Efficient Sorts. Divide and Conquer Divide and Conquer : chop a problem into smaller problems, solve those – Ex: binary search.
Quicksort CS 3358 Data Structures. Sorting II/ Slide 2 Introduction Fastest known sorting algorithm in practice * Average case: O(N log N) * Worst case:
25 May Quick Sort (11.2) CSE 2011 Winter 2011.
Quicksort COMP171 Fall Sorting II/ Slide 2 Introduction * Fastest known sorting algorithm in practice * Average case: O(N log N) * Worst case: O(N.
Chapter 7: Sorting Algorithms
1 Today’s Material Divide & Conquer (Recursive) Sorting Algorithms –QuickSort External Sorting.
CS 201 Data Structures and Algorithms Text: Read Weiss, § 7.7
Quicksort, Mergesort, and Heapsort. Quicksort Fastest known sorting algorithm in practice  Caveats: not stable  Vulnerable to certain attacks Average.
Sorting Algorithms and Average Case Time Complexity
Data Structures and Algorithms PLSD210 Sorting. Card players all know how to sort … First card is already sorted With all the rest, ¶Scan back from the.
1 Sorting Problem: Given a sequence of elements, find a permutation such that the resulting sequence is sorted in some order. We have already seen: –Insertion.
CS203 Programming with Data Structures Sorting California State University, Los Angeles.
Quicksort Divide-and-Conquer. Quicksort Algorithm Given an array S of n elements (e.g., integers): If array only contains one element, return it. Else.
Topic 17 Fast Sorting "The bubble sort seems to have nothing to recommend it, except a catchy name and the fact that it leads to some interesting theoretical.
Fundamentals of Algorithms MCS - 2 Lecture # 16. Quick Sort.
CS 206 Introduction to Computer Science II 12 / 09 / 2009 Instructor: Michael Eckmann.
1 TCSS 342, Winter 2005 Lecture Notes Sorting Weiss Ch. 8, pp
Quicksort. 2 Introduction * Fastest known sorting algorithm in practice * Average case: O(N log N) * Worst case: O(N 2 ) n But, the worst case seldom.
CS2420: Lecture 10 Vladimir Kulyukin Computer Science Department Utah State University.
Sorting. Introduction Assumptions –Sorting an array of integers –Entire sort can be done in main memory Straightforward algorithms are O(N 2 ) More complex.
Quicksort.
1 Chapter 7 Sorting Sorting of an array of N items A [0], A [1], A [2], …, A [N-1] Sorting in ascending order Sorting in main memory (internal sort)
CSC 2300 Data Structures & Algorithms March 20, 2007 Chapter 7. Sorting.
1 7.5 Heapsort Average number of comparison used to heapsort a random permutation of N items is 2N logN - O (N log log N).
Sorting Rearrange n elements into ascending order. 7, 3, 6, 2, 1  1, 2, 3, 6, 7.
Chapter 7 (Part 2) Sorting Algorithms Merge Sort.
CS2420: Lecture 11 Vladimir Kulyukin Computer Science Department Utah State University.
Sorting II/ Slide 1 Lecture 24 May 15, 2011 l merge-sorting l quick-sorting.
CS 202, Spring 2003 Fundamental Structures of Computer Science II Bilkent University1 Sorting - 3 CS 202 – Fundamental Structures of Computer Science II.
CSE 373 Data Structures Lecture 19
Sorting (Part II: Divide and Conquer) CSE 373 Data Structures Lecture 14.
Divide-And-Conquer Sorting Small instance.  n
1 Data Structures and Algorithms Sorting. 2  Sorting is the process of arranging a list of items into a particular order  There must be some value on.
Sorting Sorting includes internal sorting and external sorting – Internal sorting: the entire sort can be done in main memory, i.e., all elements needed.
Merge Sort. What Is Sorting? To arrange a collection of items in some specified order. Numerical order Lexicographical order Input: sequence of numbers.
Quicksort, Mergesort, and Heapsort. Quicksort Fastest known sorting algorithm in practice  Caveats: not stable  Vulnerable to certain attacks Average.
1 Sorting Algorithms Sections 7.1 to Comparison-Based Sorting Input – 2,3,1,15,11,23,1 Output – 1,1,2,3,11,15,23 Class ‘Animals’ – Sort Objects.
Sorting CSIT 402 Data Structures II. 2 Sorting (Ascending Order) Input ›an array A of data records ›a key value in each data record ›a comparison function.
Divide And Conquer A large instance is solved as follows:  Divide the large instance into smaller instances.  Solve the smaller instances somehow. 
Sorting: Advanced Techniques Smt Genap
CS 146: Data Structures and Algorithms July 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
FALL 2005CENG 213 Data Structures1 Priority Queues (Heaps) Reference: Chapter 7.
Sorting Fundamental Data Structures and Algorithms Aleks Nanevski February 17, 2004.
Divide and Conquer Sorting Algorithms COMP s1 Sedgewick Chapters 7 and 8.
PREVIOUS SORTING ALGORITHMS  BUBBLE SORT –Time Complexity: O(n 2 ) For each item, make (n –1) comparisons Gives: Comparisons = (n –1) + (n – 2)
Nothing is particularly hard if you divide it into small jobs. Henry Ford Nothing is particularly hard if you divide it into small jobs. Henry Ford.
QuickSort. Yet another sorting algorithm! Usually faster than other algorithms on average, although worst-case is O(n 2 ) Divide-and-conquer: –Divide:
Sorting Ordering data. Design and Analysis of Sorting Assumptions –sorting will be internal (in memory) –sorting will be done on an array of elements.
CS 367 Introduction to Data Structures Lecture 11.
Intro. to Data Structures Chapter 7 Sorting Veera Muangsin, Dept. of Computer Engineering, Chulalongkorn University 1 Chapter 7 Sorting Sort is.
Chapter 5 Sorting There are several easy algorithms to sort in O(N 2 ), such as insertion sort. There is an algorithm, Shellsort, that is very simple to.
Sorting – Lecture 3 More about Merge Sort, Quick Sort.
1 Priority Queues (Heaps). 2 Priority Queues Many applications require that we process records with keys in order, but not necessarily in full sorted.
Quick-Sort 9/13/2018 1:15 AM Quick-Sort     2
Chapter 7 Sorting Spring 14
Fast Sorting "The bubble sort seems to have nothing to recommend it, except a catchy name and the fact that it leads to some interesting theoretical problems."
Chapter 4: Divide and Conquer
Quick Sort (11.2) CSE 2011 Winter November 2018.
Yan Shi CS/SE 2630 Lecture Notes
Topic 17 Faster Sorting "The bubble sort seems to have nothing to recommend it, except a catchy name and the fact that it leads to some interesting theoretical.
Chapter 4.
CSE 326: Data Structures Sorting
EE 312 Software Design and Implementation I
CSE 373 Data Structures and Algorithms
Merge Sort (11.1) CSE 2011 Winter April 2019.
Fundamental Structures of Computer Science II
Design and Analysis of Algorithms
Presentation transcript:

1 Heapsort, Mergesort, and Quicksort Sections 7.5 to 7.7

2 Heapsort Build a binary minHeap of N elements –O(N) time Then perform N deleteMin operations –log(N) time per deleteMin Total complexity O(N log N) However it requires an extra array to store results –In addition to the heap To eliminate this requirement –Using heap to store sorted elements –Using maxHeap instead of minHeap

3 Example (MaxHeap) After BuildHeap After first deleteMax

4 Heapsort Implementation // Standard heapsort. template void heapsort( vector & a ) { // build heap for( int i = a.size( ) / 2 - 1; i >= 0; --i ) percDown( a, i, a.size( ) ); // deleteMax for( int j = a.size( ) - 1; j > 0; --j ) { std::swap( a[ 0 ], a[ j ] ); percDown( a, 0, j ); } /* Internal method for heapsort. * i is the index of an item in the heap. * Returns the index of the left child. */ inline int leftChild( int i ) { return 2 * i + 1; } /** * Internal method for heapsort that is used in * deleteMax and buildHeap. * i is the position from which to percolate down. * n is the logical size of the binary heap. */ template void percDown( vector & a, int i, int n ) { int child; Comparable tmp; for( tmp = std::move( a[ i ] ); leftChild( i ) < n; i = child ) { child = leftChild( i ); if( child != n - 1 && a[ child ] < a[ child + 1 ] ) ++child; if( tmp < a[ child ] ) a[ i ] = std::move( a[ child ] ); else break; } a[ i ] = std::move( tmp ); }

5 Mergesort Divide the N values to be sorted into two halves Recursively sort each half using Mergesort –Base case N=1  no sorting required Merge the two (sorted) halves –O(N) operation Complexity?? –We’ll see

6 Mergesort Implementation // Mergesort algorithm (driver). template void mergeSort( vector & a ) { vector tmpArray( a.size( ) ); mergeSort( a, tmpArray, 0, a.size( ) - 1 ); } /** * Internal method that makes recursive calls. * a is an array of Comparable items. * tmpArray is an array to place the merged result. * left is the left-most index of the subarray. * right is the right-most index of the subarray. */ template void mergeSort( vector & a, vector & tmpArray, int left, int right ) { if( left < right ) { int center = ( left + right ) / 2; mergeSort( a, tmpArray, left, center ); mergeSort( a, tmpArray, center + 1, right ); merge( a, tmpArray, left, center + 1, right ); }

7 /** * Internal method that merges two sorted halves of a subarray. * a is an array of Comparable items. * tmpArray is an array to place the merged result. * leftPos is the left-most index of the subarray. * rightPos is the index of the start of the second half. * rightEnd is the right-most index of the subarray. */ template void merge( vector & a, vector & tmpArray, int leftPos, int rightPos, int rightEnd ) { int leftEnd = rightPos - 1; int tmpPos = leftPos; int numElements = rightEnd - leftPos + 1; // Main loop while( leftPos <= leftEnd && rightPos <= rightEnd ) if( a[ leftPos ] <= a[ rightPos ] ) tmpArray[ tmpPos++ ] = std::move( a[ leftPos++ ] ); else tmpArray[ tmpPos++ ] = std::move( a[ rightPos++ ] ); while( leftPos <= leftEnd ) // Copy rest of first half tmpArray[ tmpPos++ ] = std::move( a[ leftPos++ ] ); while( rightPos <= rightEnd ) // Copy rest of right half tmpArray[ tmpPos++ ] = std::move( a[ rightPos++ ] ); // Copy tmpArray back for( int i = 0; i < numElements; ++i, --rightEnd ) a[ rightEnd ] = std::move( tmpArray[ rightEnd ] ); }

8 Complexity analysis Let T(N) be the complexity when size is N Recurrence relation –T(N) = 2T(N/2) + N –T(N) = 4T(N/4) + 2N –T(N) = 8T(N/8) + 3N –… –T(N) = 2 k T(N/2 k ) + k*N –For k = log N T(N) = N T(1) + N log N Complexity: O(NlogN)

9 Quicksort Fastest known sorting algorithm in practice –Caveats: not stable –Vulnerable to certain attacks Average case complexity  O(N log N ) Worst-case complexity  O(N 2 ) –Rarely happens, if coded correctly

10 Quicksort Outline Divide and conquer approach Given array S to be sorted If size of S < 1 then done; Pick any element v in S as the pivot Partition S-{v} (remaining elements in S ) into two groups S1 = {all elements in S-{v} that are smaller than v } S2 = {all elements in S-{v} that are larger than v } Return { quicksort(S1) followed by v followed by quicksort(S2) } Trick lies in handling the partitioning (step 3). –Picking a good pivot –Efficiently partitioning in-place

11 Quicksort example Select pivot partition Recursive call Merge

12 Picking the Pivot How would you pick one? Strategy 1: Pick the first element in S –Works only if input is random –What if input S is sorted, or even mostly sorted? All the remaining elements would go into either S1 or S2 ! Terrible performance! –Why worry about sorted input? Remember  Quicksort is recursive, so sub-problems could be sorted Plus mostly sorted input is quite frequent

13 Picking the Pivot (contd.) Strategy 2: Pick the pivot randomly –Would usually work well, even for mostly sorted input –Unless the random number generator is not quite random! –Plus random number generation is an expensive operation

14 Picking the Pivot (contd.) Strategy 3: Median-of-three Partitioning –Ideally, the pivot should be the median of input array S Median = element in the middle of the sorted sequence –Would divide the input into two almost equal partitions –Unfortunately, its hard to calculate median quickly, without sorting first! –So find the approximate median Pivot = median of the left-most, right-most and center element of the array S Solves the problem of sorted input

15 Picking the Pivot (contd.) Example: Median-of-three Partitioning –Let input S = {6, 1, 4, 9, 0, 3, 5, 2, 7, 8} –left=0 and S[left] = 6 –right=9 and S[right] = 8 –center = (left+right)/2 = 4 and S[center] = 0 –Pivot = Median of S[left], S[right], and S[center] = median of 6, 8, and 0 = S[left] = 6

16 Partitioning Algorithm Original input : S = {6, 1, 4, 9, 0, 3, 5, 2, 7, 8} Get the pivot out of the way by swapping it with the last element Have two ‘iterators’ – i and j –i starts at first element and moves forward –j starts at last element and moves backwards pivot ijpivot

17 Partitioning Algorithm (contd.)  While (i < j) –Move i to the right till we find a number greater than pivot –Move j to the left till we find a number smaller than pivot –If (i < j) swap(S[i], S[j]) –(The effect is to push larger elements to the right and smaller elements to the left) 4.Swap the pivot with S[i]

18 Partitioning Algorithm Illustrated ijpivot ij pivot ijpivot Move swap ijpivot move ijpivot swap ijpivot move ij pivot Swap S[i] with pivot i and j have crossed

19 Dealing with small arrays For small arrays (say, N ≤ 20), –Insertion sort is faster than quicksort Quicksort is recursive –So it can spend a lot of time sorting small arrays Hybrid algorithm: –Switch to using insertion sort when problem size is small (say for N < 20 )

20 Quicksort Driver Routine /** * Quicksort algorithm (driver). */ template void quicksort( vector & a ) { quicksort( a, 0, a.size( ) - 1 ); }

/** * Return median of left, center, and right. * Order these and hide the pivot. */ template const Comparable & median3( vector & a, int left, int right ) { int center = ( left + right ) / 2; if( a[ center ] < a[ left ] ) std::swap( a[ left ], a[ center ] ); if( a[ right ] < a[ left ] ) std::swap( a[ left ], a[ right ] ); if( a[ right ] < a[ center ] ) std::swap( a[ center ], a[ right ] ); // Place pivot at position right - 1 std::swap( a[ center ], a[ right - 1 ] ); return a[ right - 1 ]; } 21 Quicksort Pivot Selection Routine Swap a[left], a[center] and a[right] in-place Pivot is in a[center] now Swap the pivot a[center] with a[right-1]

/*a is an array of Comparable items. * left is the left-most index of the subarray. right is the right-most index of the subarray. */ template void quicksort( vector & a, int left, int right ) { if( left + 10 <= right ) { const Comparable & pivot = median3( a, left, right ); // has a side effect // Begin partitioning int i = left, j = right - 1; for( ; ; ) { while( a[ ++i ] < pivot ) { } while( pivot < a[ --j ] ) { } if( i < j ) std::swap( a[ i ], a[ j ] ); else break; } std::swap( a[ i ], a[ right - 1 ] ); // Restore pivot quicksort( a, left, i - 1 ); // Sort small elements quicksort( a, i + 1, right ); // Sort large elements } else // Do an insertion sort on the subarray insertionSort( a, left, right ); } 22 Quicksort routine move swap

23 Exercise: Runtime analysis Worst-case Average case Best case

24 Reading Assignment Chapter 9 Graph Algorithms