Quicksort CSC 172. Quicksort The basic quicksort algorithm is recursive Chosing the pivot Deciding how to partition Dealing with duplicates Wrong decisions.

Slides:



Advertisements
Similar presentations
Chapter 9 continued: Quicksort
Advertisements

Algorithms Analysis Lecture 6 Quicksort. Quick Sort Divide and Conquer.
Sorting Chapter 8 CSCI 3333 Data Structures.
CS4413 Divide-and-Conquer
Stephen P. Carl - CS 2421 Recursive Sorting Algorithms Reading: Chapter 5.
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.
Quicksort CSE 331 Section 2 James Daly. Review: Merge Sort Basic idea: split the list into two parts, sort both parts, then merge the two lists
Efficient Sorts. Divide and Conquer Divide and Conquer : chop a problem into smaller problems, solve those – Ex: binary search.
CSE 373: Data Structures and Algorithms
Quicksort CS 3358 Data Structures. Sorting II/ Slide 2 Introduction Fastest known sorting algorithm in practice * Average case: O(N log N) * Worst case:
CSC2100B Quick Sort and Merge Sort Xin 1. Quick Sort Efficient sorting algorithm Example of Divide and Conquer algorithm Two phases ◦ Partition phase.
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
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.
© 2004 Goodrich, Tamassia QuickSort1 Quick-Sort     29  9.
CSC 2300 Data Structures & Algorithms March 23, 2007 Chapter 7. Sorting.
Lecture 7COMPSCI.220.FS.T Algorithm MergeSort John von Neumann ( 1945 ! ): a recursive divide- and-conquer approach Three basic steps: –If 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.
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.
CS 206 Introduction to Computer Science II 04 / 27 / 2009 Instructor: Michael Eckmann.
CS 206 Introduction to Computer Science II 12 / 09 / 2009 Instructor: Michael Eckmann.
Quicksort CSC 172 SPRING 2002 LECTURE 13. Quicksort The basic quicksort algorithm is recursive Chosing the pivot Deciding how to partition Dealing with.
CSC 2300 Data Structures & Algorithms March 27, 2007 Chapter 7. Sorting.
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.
Quicksort CSC 172 SPRING 2004 LECTURE 10. Reminders  Project 2 (polynomial linked-list) is due, tomorrow  Wed, 18 th 5PM  Computer Science Office –
Divide and Conquer Sorting
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).
Chapter 7 (Part 2) Sorting Algorithms Merge Sort.
Mergesort and Quicksort Chapter 8 Kruse and Ryba.
CS 206 Introduction to Computer Science II 12 / 08 / 2008 Instructor: Michael Eckmann.
CS2420: Lecture 11 Vladimir Kulyukin Computer Science Department Utah State University.
Sorting (Part II: Divide and Conquer) CSE 373 Data Structures Lecture 14.
DIVIDE & CONQUR ALGORITHMS Often written as first as a recursive algorithm Master’s Theorem: T(n) = aT(n/b) + cn i, for some constant integer i, and constants.
Algorithm Analysis 2P03 © Dave Bockus Acknowledgments to Mark Allen Weiss 2014 Data Structures & Algorithm Analysis in Java.
1 Time Analysis Analyzing an algorithm = estimating the resources it requires. Time How long will it take to execute? Impossible to find exact value Depends.
Recursive Quicksort Data Structures in Java with JUnit ©Rick Mercer.
Quicksort, Mergesort, and Heapsort. Quicksort Fastest known sorting algorithm in practice  Caveats: not stable  Vulnerable to certain attacks Average.
Sorting Algorithms 2. Quicksort General Quicksort Algorithm: Select an element from the array to be the pivot Select an element from the array to be the.
Sorting What makes it hard? Chapter 7 in DS&AA Chapter 8 in DS&PS.
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.
1 CSE 373 Sorting 3: Merge Sort, Quick Sort reading: Weiss Ch. 7 slides created by Marty Stepp
Divide-and-Conquer The most-well known algorithm design strategy: 1. Divide instance of problem into two or more smaller instances 2.Solve smaller instances.
Sorting: Advanced Techniques Smt Genap
© 2004 Goodrich, Tamassia Quick-Sort     29  9.
PREVIOUS SORTING ALGORITHMS  BUBBLE SORT –Time Complexity: O(n 2 ) For each item, make (n –1) comparisons Gives: Comparisons = (n –1) + (n – 2)
Towers of Hanoi Move n (4) disks from pole A to pole B such that a larger disk is never put on a smaller disk A BC ABC.
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.
Sorting Ordering data. Design and Analysis of Sorting Assumptions –sorting will be internal (in memory) –sorting will be done on an array of elements.
Intro. to Data Structures Chapter 7 Sorting Veera Muangsin, Dept. of Computer Engineering, Chulalongkorn University 1 Chapter 7 Sorting Sort is.
1 Chapter 7 Quicksort. 2 About this lecture Introduce Quicksort Running time of Quicksort – Worst-Case – Average-Case.
Quicksort The basic quicksort algorithm is recursive Chosing the pivot
Quick-Sort 9/12/2018 3:26 PM Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia,
Quick-Sort To understand quick-sort, let’s look at a high-level description of the algorithm 1) Divide : If the sequence S has 2 or more elements, select.
Quicksort "There's nothing in your head the sorting hat can't see. So try me on and I will tell you where you ought to be." -The Sorting Hat, Harry Potter.
Chapter 4: Divide and Conquer
Quick Sort (11.2) CSE 2011 Winter November 2018.
CSE 326: Data Structures Sorting
EE 312 Software Design and Implementation I
CSE 373 Data Structures and Algorithms
Quick-Sort 4/25/2019 8:10 AM Quick-Sort     2
Data Structures & Algorithms
Design and Analysis of Algorithms
CSE 332: Sorting II Spring 2016.
Presentation transcript:

Quicksort CSC 172

Quicksort The basic quicksort algorithm is recursive Chosing the pivot Deciding how to partition Dealing with duplicates Wrong decisions give quadratic run times Good decisions give n log n run time

The Quicksort Algorithm The basic algorithm Quicksort(S) has 4 steps 1. If the number of elements in S is 0 or 1, return 2. Pick any element v in S. It is called the pivot. 3. Partition S – {v} (the remaining elements in S) into two disjoint groups L = {x  S – {v}|x  v} R = {x  S – {v}|x  v} 4. Return the results of Quicksort(L) followed by v followed by Quicksort(R)

Write The Quicksort Algorithm The basic algorithm Quicksort(S) has 4 steps 1. If the number of elements in S is 0 or 1, return 2. Pick any element v in S. It is called the pivot. 3. Partition S – {v} (the remaining elements in S) into two disjoint groups L = {x  S – {v}|x  v} R = {x  S – {v}|x  v} 1. Return the results of Quicksort(L) followed by v followed by Quicksort(R) (assume partition(pivot,list) & append(l1,piv,l2))

Write The Quicksort Algorithm The basic algorithm Quicksort(S) has 4 steps 1. If the number of elements in S is 0 or 1, return 2. Pick any element v in S. It is called the pivot. 3. Partition S – {v} (the remaining elements in S) into two disjoint groups L = {x  S – {v}|x  v} R = {x  S – {v}|x  v} 1. Return the results of Quicksort(L) followed by v followed by Quicksort(R) (assume partition(pivot,list) & append(l1,piv,l2))

public static Node qsort(Node n) { Node list = n; if ((list == null) || (list.next == null) return list; Comparable pivot = list.data; list = list.next; Node secondList = partition(pivot,list); return append(qsort(list),pivot,qsort(secondList)); }

Some Observations Multibase case (0 and 1) Any element can be used as the pivot The pivot divides the array elements into two groups elements smaller than the pivot elements larger than the pivot Some choice of pivots are better than others The best choice of pivots equally divides the array Elements equal to the pivot can go in either group

Example

Example

Example

Example

Example

Example

Example

Example

Example

Example

Example

Example

Example

Example

Example

Example

Example

Example

Example

Example

Example

Example

Example

Example

Example

Running Time What is the running time of Quicksort? Depends on how well we pick the pivot So, we can look at Best case Worst case Average (expected) case

Worst case (give me the bad news first) What is the worst case? What would happen if we called Quicksort (as shown in the example) on the sorted array?

Example

Example

Example

Example

Example

Example

Example How high will this tree call stack get?

Worst Case T(n) = T(n-1) + n For the recursive call For the comparisons in the partitioning

Worst case expansion T(n) = T(n-1) + n T(n) = T(n-2) + (n-1) + n T(n) = T(n-3) + (n-2) + (n-1) + n …. T(n) = T(n-(n-1)) … + (n-2)+(n-1) +n T(n) = … + (n-2)+(n-1) +n T(n) = n(n+1)/2 = O(n 2 )

Best Case Intuitively, the best case for quicksort is that the pivot partitons the set into two equally sized subsets and that this partitioning happens at every level Then, we have two half sized recursive calls plus linear overhead T(n) = 2T(n/2) + n O(n log n) Just like our old friend, MergeSort

Best Case More precisely, consider how much work is done at each “level” We can think of the quick-sort “tree” Let s i (n) denote the sum of the input sizes of the nodes at depth i in the tree

Example

Example

Example

Example

Example

Example

Example

Example

Example

Example

What is size at each level? n n-1 n-3 n-7 What is the general rule?

Best Case, more precisely S 0 (n) = n S 1 (n) = n - 1 S 2 (n) = (n – 1) – 2 = n – (1 + 2) = n-3 S 3 (n) = ((n – 1) – 2) - 4 = n – ( ) = n-7 … S i (n) = n – ( … + 2 i-1 ) = n - 2 i + 1 Height is O(log n) No more than n work is done at any one level Best case time complexity is O(n log n)

Average case QuickSort Because the run time of quicksort can vary, we would like to know the average performance. The cost to quicksort N items equals N units for the partitioning plus the cost of the two recursive calls The average cost of each recursive call equals the average over all possible sub-problem sizes

Average cost of the recursive calls

Recurrence Relation

Telescoping ……

So (Weiss p. 300!), Nth Harmonic no is O(log N),+Euler-3/2

Intuitively f(x)= 1/x 1 n area = log(x) 2 3 1/2 1/3

Picking the Pivot A fast choice is important NEVER use the first (or last) element as the pivot! Sorted (or nearly sorted) arrays will end up with quadratic run times. The middle element is reasonable x[(low+high)/2] but there could be some bad cases

Median of three partitioning Take the median (middle value) of the first, last, middle

In place partitioning Pick the pivot Swap the pivot with the last element Scanning Run i from left to right when i encounters a large element, stop Run j from right to left when j encounters a small element, stop If i and j have not crossed, swap values and continue scanning If i and j have crossed, swap the pivot with element i

Example Quicksort(a,0,9) Quicksort(a,low,high)

Example

i j

i j

i j

i j

i j

i j

i j

i j

i j

i j

i j

i j

i j Now, Quicksort(a,low,i-1) and Quicksort(a,i+1,high)

Java Quicksort public static void quicksort(Comparable [] a) { quicksort(a,0,a.length-1); }

public static void quicksort(Comparable [] a,int low, int high) { if (low + CUTOFF > high) insertionSort(a,low,high); else { int middle = (low + high)/2; if (a[middle].compareTo(a[low]) < 0) swap(a,low,middle); if (a[high].compareTo(a[low]) < 0) swap(a,low,high); if (a[high].compareTo(a[middle]) < 0) swap(a,middle,high); swap(a,middle,high-1); Comparable pivot = a[high-1];

int i,j; for (i=low;j=high-1;;) { while(a[++i].compareTo(pivot) < 0) ; while(pivot.compareTo(a[--j]) < 0) ; if (i >= j) break; swap(a,i,j); } swap(a,i,high-1); quicksort(a,low,i-1); quicksort(a,i+1;high); }