QUICKSORT 2015-T2 Lecture 16 School of Engineering and Computer Science, Victoria University of Wellington COMP 103 Marcus Frean.

Slides:



Advertisements
Similar presentations
Introduction to Algorithms Quicksort
Advertisements

Garfield AP Computer Science
Algorithms Analysis Lecture 6 Quicksort. Quick Sort Divide and Conquer.
CS Section 600 CS Section 002 Dr. Angela Guercio Spring 2010.
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.
Efficient Sorts. Divide and Conquer Divide and Conquer : chop a problem into smaller problems, solve those – Ex: binary search.
ISOM MIS 215 Module 7 – Sorting. ISOM Where are we? 2 Intro to Java, Course Java lang. basics Arrays Introduction NewbieProgrammersDevelopersProfessionalsDesigners.
Sorting. “Sorting” When we just say “sorting,” we mean in ascending order (smallest to largest) The algorithms are trivial to modify if we want to sort.
CSC2100B Quick Sort and Merge Sort Xin 1. Quick Sort Efficient sorting algorithm Example of Divide and Conquer algorithm Two phases ◦ Partition phase.
Copyright (C) Gal Kaminka Data Structures and Algorithms Sorting II: Divide and Conquer Sorting Gal A. Kaminka Computer Science Department.
Sorting Algorithms and Average Case Time Complexity
CMPS1371 Introduction to Computing for Engineers SORTING.
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 171: Introduction to Computer Science II Quicksort.
CS 206 Introduction to Computer Science II 12 / 09 / 2009 Instructor: Michael Eckmann.
Sorting21 Recursive sorting algorithms Oh no, not again!
Lecture 25 Selection sort, reviewed Insertion sort, reviewed Merge sort Running time of merge sort, 2 ways to look at it Quicksort Course evaluations.
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.
TDDB56 DALGOPT-D DALG-C Lecture 8 – Sorting (part I) Jan Maluszynski - HT Sorting: –Intro: aspects of sorting, different strategies –Insertion.
Quicksort.
Chapter 7 (Part 2) Sorting Algorithms Merge Sort.
Mergesort and Quicksort Chapter 8 Kruse and Ryba.
Sorting II/ Slide 1 Lecture 24 May 15, 2011 l merge-sorting l quick-sorting.
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.
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.
A review session 2013-T2 Lecture 16 School of Engineering and Computer Science, Victoria University of Wellington COMP 103 Marcus Frean.
FASTER SORTING using RECURSION : QUICKSORT COMP 103.
Computer Science 101 Fast Searching and Sorting. Improving Efficiency We got a better best case by tweaking the selection sort and the bubble sort We.
Merge Sort. What Is Sorting? To arrange a collection of items in some specified order. Numerical order Lexicographical order Input: sequence of numbers.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArraySet and Binary Search.
FASTER SORTING using RECURSION : QUICKSORT 2014-T2 Lecture 16 School of Engineering and Computer Science, Victoria University of Wellington COMP 103 Marcus.
Sorting. Pseudocode of Insertion Sort Insertion Sort To sort array A[0..n-1], sort A[0..n-2] recursively and then insert A[n-1] in its proper place among.
An introduction to costs (continued), and Binary Search 2013-T2 Lecture 11 School of Engineering and Computer Science, Victoria University of Wellington.
SORTING 2014-T2 Lecture 13 School of Engineering and Computer Science, Victoria University of Wellington COMP 103 Marcus Frean.
2011-T2 Lecture 21 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, and Peter Andreae, VUW.
1 CSE 373 Sorting 3: Merge Sort, Quick Sort reading: Weiss Ch. 7 slides created by Marty Stepp
Review 1 Selection Sort Selection Sort Algorithm Time Complexity Best case Average case Worst case Examples.
Big-O and Sorting February 6, Administrative Stuff Readings for today: Ch Readings for tomorrow: Ch 8.
FASTER SORT using RECURSION : MERGE SORT 2015-T2 Lecture 15 School of Engineering and Computer Science, Victoria University of Wellington COMP 103 Marcus.
2015-T2 Lecture 17 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, John Lewis,
Computer Science 101 Fast Algorithms. What Is Really Fast? n O(log 2 n) O(n) O(n 2 )O(2 n )
1 Heapsort, Mergesort, and Quicksort Sections 7.5 to 7.7.
Data Structures - CSCI 102 Selection Sort Keep the list separated into sorted and unsorted sections Start by finding the minimum & put it at the front.
ICS201 Lecture 21 : Sorting King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Fast Sorting COMP
Divide and Conquer Sorting Algorithms COMP s1 Sedgewick Chapters 7 and 8.
Sorting Algorithms Merge Sort Quick Sort Hairong Zhao New Jersey Institute of Technology.
PREVIOUS SORTING ALGORITHMS  BUBBLE SORT –Time Complexity: O(n 2 ) For each item, make (n –1) comparisons Gives: Comparisons = (n –1) + (n – 2)
Review Quick Sort Quick Sort Algorithm Time Complexity Examples
Today’s Material Sorting: Definitions Basic Sorting Algorithms
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.
CS 367 Introduction to Data Structures Lecture 11.
FASTER SORT using RECURSION : MERGE SORT COMP 103.
Sorting – Lecture 3 More about Merge Sort, Quick Sort.
329 3/30/98 CSE 143 Searching and Sorting [Sections 12.4, ]
CMPT 238 Data Structures More on Sorting: Merge Sort and Quicksort.
FASTER SORT using RECURSION : MERGE SORT
COMP 103 SORTING Lindsay Groves 2016-T2 Lecture 26
Chapter 7 Sorting Spring 14
More complexity analysis & Binary Search
CSE 143 Lecture 23: quick sort.
Chapter 4: Divide and Conquer
CSC215 Lecture Algorithms.
Data Structures Review Session
slides adapted from Marty Stepp
CSE 373 Data Structures and Algorithms
Presentation transcript:

QUICKSORT 2015-T2 Lecture 16 School of Engineering and Computer Science, Victoria University of Wellington COMP 103 Marcus Frean

2 RECAP-TODAY RECAP  MergeSort – a sorting algorithm that exploits recursion TODAY  QuickSort  The cost of MergeSort and QuickSort  O(n log n) ANNOUNCEMENTS  Assignment 5 is due this Friday  Test is being marked sorting algorithms put to music: (quicksort is at 38 sec)

3 Divide and Conquer Sorts To Sort:  Split  Sort each part (recursive)  Combine Where does the work happen ?  MergeSort:  split is trivial  combine does all the work  QuickSort:  split does all the work  combine is trivial Array Sorted Array Split Combine SubArray SortedSubArray Sort Split Combine SubArray Sort SortedSubArray Split Combine SubArray Sort SortedSubArray

4 QuickSort  uses Divide and Conquer, but does its work in the “split” step  split the array into parts, by choosing a “pivot” item, and making sure that: all items < pivot are in the left part all items > pivot are in the right part  Then (recursively) sort each part Here's how we start it off: public static void quickSort( E[] data, int size, Comparator comp) { quickSort (data, 0, size, comp); } “wrapper” version starts it off recursive version carries it on (and on...) note: it won’t usually be an equal split

5 QuickSort – the recursion public static void quickSort(E[ ] data, int low, int high, Comparator comp){ if (high-low < 2) // only one item to sort. return; if (high - low < 4) // only two or three items to sort. sort3(data, low, high, comp); else { // split into two parts, mid = index of boundary int mid = partition(data, low, high, comp); quickSort(data, low, mid, comp); quickSort(data, mid, high, comp); }

6 QuickSort: simplest version 1. Choose a pivot: pivot Use pivot to partition the array: not yet sorted

7 QuickSort: in-place version 1. Choose a pivot: pivot Use pivot to partition the array: low high left (gets returned) not yet sorted

8 QuickSort: coding in-place partition /** Partition into small items (low..mid-1) and large items (mid..high-1) private static int partition(E[] data, int low, int high, Comparator comp){ E pivot = int left = low-1; int right = high; while( left <= right ){ do { left++; // just skip over items on the left < pivot } while (left<high &&comp.compare(data[left], pivot)< 0); do { right--; // just skip over items on the right > pivot } while (right>=low && comp.compare(data[right], pivot)> 0); if (left < right) swap(data, left, right); } return left; } data[low];// simple but poor choice! median(data[low], data[high-1], data[(low+high)/2], comp);

9 QuickSort data array : [p a1 r f e q2 w q1 t z2 x c v b z1 a2 ] indexes : [ ] do : [p a1 r f e q2 w q1 t z2 x c v b z1 a2 ] p ->6 : [a2 a1 b f e c w q1 t z2 x q2 v r z1 p ] do 0..6 : [a2 a1 b f e c ] c ->4 : [a2 a1 b c e f ] do 0..4 : [a2 a1 b c ] b ->3 : [a2 a1 b c ] do 0..3 : [a2 a1 b ] done 0..3 : [a2 a1 b ] do 3..4 : [ c ] done 0..4 : [a2 a1 b c ] do 4..6 : [ e f ] done 4..6 : [ e f ] done 0..6 : [a2 a1 b c e f ] do : [ w q1 t z2 x q2 v r z1 p ] q2 ->8 : [ p q2 t z2 x q1 v r z1 w ] do 6..8 : [ p q2 ] done 6..8 : [ p q2 ]

10 Quick Sort do : [ w q1 t z2 x q2 v r z1 p ] : [ p q2 t z2 x q1 v r z1 w ] do 6..8 : [ p q2 ] done 6..8 : [ p q2 ] do : [ t z2 x q1 v r z1 w ] ->12: [ t r v q1 x z2 z1 w ] do : [ t r v q1 ] ->10: [ q1 r v t ] do : [ q1 r ] done : [ q1 r ] do : [ v t ] done : [ t v ] done : [ q1 r t v ] do : [ x z2 z1 w ] ->13: [ w z2 z1 x ] do : [ w ] do : [ z2 z1 x ] done : [ x z2 z1 ] done : [ w x z2 z1 ] done : [ q1 r t v w x z2 z1 ] done : [ p q2 q1 r t v w x z2 z1 ] done : [a2 a1 b c e f p q2 q1 r t v w x z2 z1 ]

11 What is the computational cost of Sorting?  Insertion Sort, Selection Sort:  O(n 2 ) [except for Insertion sort on almost-sorted lists]  This is “slow”  What about Merge Sort and Quick Sort ?  There’s no inner loop!  How do you analyse recursive algorithms?

12 The cost of MergeSort private static void mergeSort (E[ ] data, E[ ] other, int low, int high, Comparator comp) { if (high > low+1) { int mid = (low+high)/2; mergeSort(other, data, low, mid, comp); mergeSort(other, data, mid, high, comp); merge(other, data, low, mid, high, comp); } }  Cost of mergeSort:  Three steps: first recursive call second recursive call merge: has to copy over (high-low) items

13 MergeSort Cost (analysis order) LEVEL 1 (two mergesorts) LEVEL 1 (merge) LEVEL 2 (two mergesorts) LEVEL 2 (merge) LEVEL 3 (two mergesorts) LEVEL 3 (merge) LEVEL 4 (two mergesorts) LEVEL 4 (merge)

14 The cost of MergeSort  Level 1:2 * n/2= n  Level 2:4 * n/4= n  Level 3:8 * n/8= n  Level 4:16 * n/16= n so in general, at any level k, there are n comparisons  How many levels ? the number of times you can halve n is log n  Total cost? = O( )  n = 1,000 n = 1,000,000

15 Analysing with Recurrence Relations private static void mergeSort(E[] data, E[] other, int low, int high, Comparator comp){ if (high > low+1){ int mid = (low+high)/2; mergeSort(other, data, low, mid, comp); mergeSort(other, data, mid, high, comp); merge(other, data, low, mid, high, comp); } }  Cost of mergeSort = C(n)  C(n) = C(n/2) + C(n/2) + n = 2 C(n/2) + n  Recurrence Relation:  (we will) Solve by repeated substitution & find pattern  (we could) Solve by general method

16 Solving Recurrence Relations C(n) = 2 C(n/2) + n = 2 [ 2 C(n/4) + n/2] + n = 4 C(n/4) + 2 n = 4 [ 2 (C(n/8) + n/4] + 2 n = 8 C(n/8) + 3 n = 16 C(n/16) + 4 n : = 2 k C( n/2 k ) + k * n when n = 2 k, k = log(n) = n C (1) + log(n) * n and since C(1) = 0, C(n) = log(n) * n

17 QuickSort public static void quickSort (E[ ] data, int low, int high, Comparator comp) { if (high > low +2) { int mid = partition(data, low, high, comp); quickSort(data, low, mid, comp); quickSort(data, mid, high, comp); } } Cost of Quick Sort:  three steps: partition: has to compare (high-low) pairs first recursive call second recursive call

18 QuickSort Cost:  If Quicksort divides the array exactly in half, then:  C(n) = n + 2 C(n/2)  n log(n) comparisons = O(n log(n)) (best case)  If Quicksort divides the array into 1 and n-1:  C(n) = n + (n-1) + (n-2) + (n-3) + … = n(n-1)/2 comparisons = O(n 2 ) (worst case)  Average case ?  very hard to analyse.  still O(n log(n)), and very good.  Quicksort is “in place”, MergeSort is not

19 Stable or Unstable ? Faster if almost-sorted ?  MergeSort:  Stable: doesn’t jump any item over an unsorted region ⇒ two equal items preserve their order  Same cost on all input  “natural merge” variant doesn’t sort already sorted regions ⇒ will be very fast: O(n) on almost sorted lists  QuickSort:  Unstable: Partition “jumps” items to the other end ⇒ two equal items likely to reverse their order  Cost depends on choice of pivot.  simplest choice is very slow: O(n 2 ) even on almost sorted lists  better choice (median of three) ⇒ O(n log(n)) on almost sorted lists

20 Some “Big-Oh” costs revisited Implementing Collections:  ArrayList: O(n) to add/remove, except at end  Stack:O(1)  ArraySet:O(n) (cost of searching)  SortedArraySetO( log(n) ) to search (with binary search) O(n) to add/remove (cost of moving up/down)  O( n 2 ) to add n items O( n log(n) ) to initialise with n items. (with fast sorting)