Quicksort CS 3358 Data Structures. Sorting II/ Slide 2 Introduction Fastest known sorting algorithm in practice * Average case: O(N log N) * Worst case:

Slides:



Advertisements
Similar presentations
Chapter 9 continued: Quicksort
Advertisements

Introduction to Algorithms Quicksort
Algorithms Analysis Lecture 6 Quicksort. Quick Sort Divide and Conquer.
CSE 3101: Introduction to the Design and Analysis of Algorithms
§7 Quicksort -- the fastest known sorting algorithm in practice 1. The Algorithm void Quicksort ( ElementType A[ ], int N ) { if ( N < 2 ) return; pivot.
ADA: 5. Quicksort1 Objective o describe the quicksort algorithm, it's partition function, and analyse its running time under different data conditions.
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.
QuickSort 4 February QuickSort(S) Fast divide and conquer algorithm first discovered by C. A. R. Hoare in If the number of elements in.
DIVIDE AND CONQUER APPROACH. General Method Works on the approach of dividing a given problem into smaller sub problems (ideally of same size).  Divide.
Spring 2015 Lecture 5: QuickSort & Selection
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.
Lecture 7COMPSCI.220.FS.T Algorithm MergeSort John von Neumann ( 1945 ! ): a recursive divide- and-conquer approach Three basic steps: –If the.
Insertion Sort Merge Sort QuickSort. Sorting Problem Definition an algorithm that puts elements of a list in a certain order Numerical order and Lexicographical.
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.
Fundamentals of Algorithms MCS - 2 Lecture # 16. Quick Sort.
CS 206 Introduction to Computer Science II 12 / 09 / 2009 Instructor: Michael Eckmann.
Quicksort. Quicksort I To sort a[left...right] : 1. if left < right: 1.1. Partition a[left...right] such that: all a[left...p-1] are less than a[p], and.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. Sorting III 1 An Introduction to Sorting.
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.
Quicksort.
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.
Unit 061 Quick Sort csc326 Information Structures Spring 2009.
Quicksort CIS 606 Spring Quicksort Worst-case running time: Θ(n 2 ). Expected running time: Θ(n lg n). Constants hidden in Θ(n lg n) are small.
Quicksort
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).
Chapter 7 (Part 2) Sorting Algorithms Merge Sort.
1 QuickSort Worst time:  (n 2 ) Expected time:  (nlgn) – Constants in the expected time are small Sorts in place.
CS 206 Introduction to Computer Science II 12 / 08 / 2008 Instructor: Michael Eckmann.
Sorting Chapter 6 Chapter 6 –Insertion Sort 6.1 –Quicksort 6.2 Chapter 5 Chapter 5 –Mergesort 5.2 –Stable Sorts Divide & Conquer.
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.
Computer Algorithms Lecture 10 Quicksort Ch. 7 Some of these slides are courtesy of D. Plaisted et al, UNC and M. Nicolescu, UNR.
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.
CSC – 332 Data Structures Sorting
Quicksort, Mergesort, and Heapsort. Quicksort Fastest known sorting algorithm in practice  Caveats: not stable  Vulnerable to certain attacks Average.
The Selection Problem. 2 Median and Order Statistics In this section, we will study algorithms for finding the i th smallest element in a set of n elements.
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.
Review 1 Selection Sort Selection Sort Algorithm Time Complexity Best case Average case Worst case Examples.
Divide And Conquer A large instance is solved as follows:  Divide the large instance into smaller instances.  Solve the smaller instances somehow. 
1 Heapsort, Mergesort, and Quicksort Sections 7.5 to 7.7.
ICS201 Lecture 21 : Sorting King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
Sorting Fundamental Data Structures and Algorithms Aleks Nanevski February 17, 2004.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Sorting.
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 Quicksort is a well-known sorting algorithm that, in the worst case, it makes Θ(n 2 ) comparisons. Typically, quicksort is significantly faster.
Quicksort This is probably the most popular sorting algorithm. It was invented by the English Scientist C.A.R. Hoare It is popular because it works well.
QuickSort. Yet another sorting algorithm! Usually faster than other algorithms on average, although worst-case is O(n 2 ) Divide-and-conquer: –Divide:
Intro. to Data Structures Chapter 7 Sorting Veera Muangsin, Dept. of Computer Engineering, Chulalongkorn University 1 Chapter 7 Sorting Sort is.
Quicksort
Chapter 7 Sorting Spring 14
Quicksort 1.
Quick Sort (11.2) CSE 2011 Winter November 2018.
EE 312 Software Design and Implementation I
Quicksort.
CSC 380: Design and Analysis of Algorithms
CSC 380: Design and Analysis of Algorithms
Quicksort.
CSE 332: Sorting II Spring 2016.
Quicksort.
Presentation transcript:

Quicksort CS 3358 Data Structures

Sorting II/ Slide 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 happens. Another divide-and-conquer recursive algorithm, like mergesort

Sorting II/ Slide 3 Quicksort * Divide step: n Pick any element (pivot) v in S n Partition S – {v} into two disjoint groups S1 = {x  S – {v} | x <= v} S2 = {x  S – {v} | x  v} * Conquer step: recursively sort S1 and S2 * Combine step: the sorted S1 (by the time returned from recursion), followed by v, followed by the sorted S2 (i.e., nothing extra needs to be done) v v S1S2 S

Sorting II/ Slide 4 Example: Quicksort

Sorting II/ Slide 5 Example: Quicksort...

Sorting II/ Slide 6 Pseudocode Input: an array A[p, r] Quicksort (A, p, r) { if (p < r) { q = Partition (A, p, r) //q is the position of the pivot element Quicksort (A, p, q-1) Quicksort (A, q+1, r) }

Sorting II/ Slide 7 Partitioning * Partitioning n Key step of quicksort algorithm n Goal: given the picked pivot, partition the remaining elements into two smaller sets n Many ways to implement n Even the slightest deviations may cause surprisingly bad results. * We will learn an easy and efficient partitioning strategy here. * How to pick a pivot will be discussed later

Sorting II/ Slide 8 Partitioning Strategy * Want to partition an array A[left.. right] * First, get the pivot element out of the way by swapping it with the last element. (Swap pivot and A[right]) * Let i start at the first element and j start at the next-to- last element (i = left, j = right – 1) pivot i j swap

Sorting II/ Slide 9 Partitioning Strategy * Want to have n A[p] <= pivot, for p < i n A[p] >= pivot, for p > j * When i < j n Move i right, skipping over elements smaller than the pivot n Move j left, skipping over elements greater than the pivot n When both i and j have stopped  A[i] >= pivot  A[j] <= pivot i j i j i j <= pivot >= pivot

Sorting II/ Slide 10 Partitioning Strategy * When i and j have stopped and i is to the left of j n Swap A[i] and A[j]  The large element is pushed to the right and the small element is pushed to the left n After swapping  A[i] <= pivot  A[j] >= pivot n Repeat the process until i and j cross swap i j i j

Sorting II/ Slide 11 Partitioning Strategy * When i and j have crossed n Swap A[i] and pivot * Result: n A[p] <= pivot, for p < i n A[p] >= pivot, for p > i i j i j i j

Sorting II/ Slide 12 Small arrays * For very small arrays, quicksort does not perform as well as insertion sort n how small depends on many factors, such as the time spent making a recursive call, the compiler, etc * Do not use quicksort recursively for small arrays n Instead, use a sorting algorithm that is efficient for small arrays, such as insertion sort

Sorting II/ Slide 13 Picking the Pivot * Use the first element as pivot n if the input is random, ok n if the input is presorted (or in reverse order)  all the elements go into S2 (or S1)  this happens consistently throughout the recursive calls  Results in O(n 2 ) behavior (Analyze this case later) * Choose the pivot randomly n generally safe n random number generation can be expensive

Sorting II/ Slide 14 Picking the Pivot * Use the median of the array n Partitioning always cuts the array into roughly half n An optimal quicksort (O(N log N)) n However, hard to find the exact median  e.g., sort an array to pick the value in the middle

Sorting II/ Slide 15 Pivot: median of three * We will use median of three n Compare just three elements: the leftmost, rightmost and center n Swap these elements if necessary so that  A[left] = Smallest  A[right] = Largest  A[center] = Median of three n Pick A[center] as the pivot n Swap A[center] and A[right – 1] so that pivot is at second last position (why?) median3

Sorting II/ Slide 16 Pivot: median of three pivot A[left] = 2, A[center] = 13, A[right] = 6 Swap A[center] and A[right] pivot Choose A[center] as pivot Swap pivot and A[right – 1] Note we only need to partition A[left + 1, …, right – 2]. Why?

Sorting II/ Slide 17 Main Quicksort Routine For small arrays Recursion Choose pivot Partitioning

Sorting II/ Slide 18 Partitioning Part * Works only if pivot is picked as median-of-three. n A[left] = pivot n Thus, only need to partition A[left + 1, …, right – 2] * j will not run past the beginning n because a[left] <= pivot * i will not run past the end n because a[right-1] = pivot

Sorting II/ Slide 19 Quicksort Faster than Mergesort * Both quicksort and mergesort take O(N log N) in the average case. * Why is quicksort faster than mergesort? n The inner loop consists of an increment/decrement (by 1, which is fast), a test and a jump. n There is no extra juggling as in mergesort. inner loop

Sorting II/ Slide 20 Analysis * Assumptions: n A random pivot (no median-of-three partitioning) n No cutoff for small arrays * Running time n pivot selection: constant time, i.e. O(1) n partitioning: linear time, i.e. O(N) n running time of the two recursive calls * T(N)=T(i)+T(N-i-1)+cN where c is a constant n i: number of elements in S1

Sorting II/ Slide 21 Worst-Case Analysis * What will be the worst case? n The pivot is the smallest element, all the time n Partition is always unbalanced

Sorting II/ Slide 22 Best-case Analysis * What will be the best case? n Partition is perfectly balanced. n Pivot is always in the middle (median of the array)

Sorting II/ Slide 23 Average-Case Analysis * Assume n Each of the sizes for S1 is equally likely * This assumption is valid for our pivoting (median-of-three) strategy * On average, the running time is O(N log N)

Sorting II/ Slide 24 Quicksort * Quicksort’s reputation * Quicksort’s implementation * Quicksort for distinct elements * Quicksort for duplicate elements * Quicksort for small arrays * Comparison of Quicksort and Mergesort

Sorting II/ Slide 25 Quicksort’s reputation * For many years, [Quicksort] had the reputation of being an algorithm that could in theory be highly optimized but in practice was impossible to code correctly

Sorting II/ Slide 26 Quicksort for Small Arrays * For very small arrays (N<= 20), quicksort does not perform as well as insertion sort * A good cutoff range is N=10 * Switching to insertion sort for small arrays can save about 15% in the running time

Sorting II/ Slide 27 Comparisons of Mergesort and Quicksort * Both run in O(nlogn) * Compared with Quicksort, Mergesort has less number of comparisons but larger number of moving elements * In Java, an element comparison is expensive but moving elements is cheap. Therefore, Mergesort is used in the standard Java library for generic sorting

Sorting II/ Slide 28 Comparisons of Mergesort and Quicksort In C++ , copying objects can be expensive while comparing objects often is relatively cheap. Therefore, quicksort is the sorting routine commonly used in C++ libraries