Quicksort (Weiss chapter 8.6)

Similar documents
Mergesort again. 1. Split the list into two equal parts

Better sorting algorithms (Weiss chapter )

Data structures. More sorting. Dr. Alex Gerdes DIT961 - VT 2018

Mergesort again. 1. Split the list into two equal parts

Sorting. Weiss chapter , 8.6

We can use a max-heap to sort data.

Real-world sorting (not on exam)

Cosc 241 Programming and Problem Solving Lecture 17 (30/4/18) Quicksort

Lecture 8: Mergesort / Quicksort Steven Skiena

Algorithmic Analysis and Sorting, Part Two

Divide and Conquer. Algorithm D-and-C(n: input size)

CSE373: Data Structure & Algorithms Lecture 21: More Comparison Sorting. Aaron Bauer Winter 2014

Algorithmic Analysis and Sorting, Part Two. CS106B Winter

Sorting Algorithms. + Analysis of the Sorting Algorithms

COSC242 Lecture 7 Mergesort and Quicksort

CSE 373: Data Structures and Algorithms

Quick Sort. CSE Data Structures May 15, 2002

BM267 - Introduction to Data Structures

Sorting. Sorting. Stable Sorting. In-place Sort. Bubble Sort. Bubble Sort. Selection (Tournament) Heapsort (Smoothsort) Mergesort Quicksort Bogosort

Overview of Sorting Algorithms

Divide and Conquer Sorting Algorithms and Noncomparison-based

Divide-and-Conquer. The most-well known algorithm design strategy: smaller instances. combining these solutions

CSC Design and Analysis of Algorithms

Sorting. Sorting in Arrays. SelectionSort. SelectionSort. Binary search works great, but how do we create a sorted array in the first place?

CS2223: Algorithms Sorting Algorithms, Heap Sort, Linear-time sort, Median and Order Statistics

Data Structures and Algorithms

CSE 332: Data Structures & Parallelism Lecture 12: Comparison Sorting. Ruth Anderson Winter 2019

Sorting. Task Description. Selection Sort. Should we worry about speed?

Faster Sorting Methods

Quick-Sort. Quick-sort is a randomized sorting algorithm based on the divide-and-conquer paradigm:

Divide and Conquer 4-0

IS 709/809: Computational Methods in IS Research. Algorithm Analysis (Sorting)

Key question: how do we pick a good pivot (and what makes a good pivot in the first place)?

CS 310 Advanced Data Structures and Algorithms

Chapter 4. Divide-and-Conquer. Copyright 2007 Pearson Addison-Wesley. All rights reserved.

Quicksort. Repeat the process recursively for the left- and rightsub-blocks.

Algorithms and Data Structures (INF1) Lecture 7/15 Hua Lu

ITEC2620 Introduction to Data Structures

SORTING AND SELECTION

CS 171: Introduction to Computer Science II. Quicksort

Randomized Algorithms, Quicksort and Randomized Selection

CS 171: Introduction to Computer Science II. Quicksort

CSC Design and Analysis of Algorithms. Lecture 6. Divide and Conquer Algorithm Design Technique. Divide-and-Conquer

Run Times. Efficiency Issues. Run Times cont d. More on O( ) notation

Problem. Input: An array A = (A[1],..., A[n]) with length n. Output: a permutation A of A, that is sorted: A [i] A [j] for all. 1 i j n.

CS S-11 Sorting in Θ(nlgn) 1. Base Case: A list of length 1 or length 0 is already sorted. Recursive Case:

DIVIDE AND CONQUER ALGORITHMS ANALYSIS WITH RECURRENCE EQUATIONS

CSE 373 MAY 24 TH ANALYSIS AND NON- COMPARISON SORTING

Programming II (CS300)

Searching, Sorting. part 1

CSE373: Data Structure & Algorithms Lecture 18: Comparison Sorting. Dan Grossman Fall 2013

2/26/2016. Divide and Conquer. Chapter 6. The Divide and Conquer Paradigm

CS 61B Summer 2005 (Porter) Midterm 2 July 21, SOLUTIONS. Do not open until told to begin

Selection (deterministic & randomized): finding the median in linear time

Programming in Haskell Aug-Nov 2015

Presentation for use with the textbook, Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, Merge Sort & Quick Sort

Lecture 2: Divide&Conquer Paradigm, Merge sort and Quicksort

Algorithms in Systems Engineering ISE 172. Lecture 12. Dr. Ted Ralphs

CS 137 Part 8. Merge Sort, Quick Sort, Binary Search. November 20th, 2017

Divide and Conquer Algorithms: Advanced Sorting. Prichard Ch. 10.2: Advanced Sorting Algorithms

Sorting. Riley Porter. CSE373: Data Structures & Algorithms 1

Sorting Goodrich, Tamassia Sorting 1

Sorting Algorithms Day 2 4/5/17

17/05/2018. Outline. Outline. Divide and Conquer. Control Abstraction for Divide &Conquer. Outline. Module 2: Divide and Conquer

Chapter 3:- Divide and Conquer. Compiled By:- Sanjay Patel Assistant Professor, SVBIT.

Unit-2 Divide and conquer 2016

CS240 Fall Mike Lam, Professor. Quick Sort

Question 7.11 Show how heapsort processes the input:

Data Structures and Algorithms

08 A: Sorting III. CS1102S: Data Structures and Algorithms. Martin Henz. March 10, Generated on Tuesday 9 th March, 2010, 09:58

Divide-and-Conquer. Dr. Yingwu Zhu

CIS 121 Data Structures and Algorithms with Java Spring Code Snippets and Recurrences Monday, January 29/Tuesday, January 30

DATA STRUCTURES AND ALGORITHMS

CS1 Lecture 30 Apr. 2, 2018

Sorting: Quick Sort. College of Computing & Information Technology King Abdulaziz University. CPCS-204 Data Structures I

CS Divide and Conquer

Divide and Conquer Algorithms: Advanced Sorting

4. Sorting and Order-Statistics

Sorting. Data structures and Algorithms

Sorting. CSE 143 Java. Insert for a Sorted List. Insertion Sort. Insertion Sort As A Card Game Operation. CSE143 Au

Sorting Algorithms. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University

Data Structure Lecture#17: Internal Sorting 2 (Chapter 7) U Kang Seoul National University

ECE 2574: Data Structures and Algorithms - Basic Sorting Algorithms. C. L. Wyatt

Sorting. CSC 143 Java. Insert for a Sorted List. Insertion Sort. Insertion Sort As A Card Game Operation CSC Picture

Sorting. Quicksort analysis Bubble sort. November 20, 2017 Hassan Khosravi / Geoffrey Tien 1

SORTING, SETS, AND SELECTION

SAMPLE OF THE STUDY MATERIAL PART OF CHAPTER 6. Sorting Algorithms

Quick-Sort fi fi fi 7 9. Quick-Sort Goodrich, Tamassia

Chapter 1 Divide and Conquer Algorithm Theory WS 2015/16 Fabian Kuhn

Algorithmic Analysis. Go go Big O(h)!

S O R T I N G Sorting a list of elements implemented as an array. In all algorithms of this handout the sorting of elements is in ascending order

Chapter 1 Divide and Conquer Algorithm Theory WS 2014/15 Fabian Kuhn

Quick-Sort. Quick-Sort 1

COMP2012H Spring 2014 Dekai Wu. Sorting. (more on sorting algorithms: mergesort, quicksort, heapsort)

Practical Session #11 - Sort properties, QuickSort algorithm, Selection

Lecture 7 Quicksort : Principles of Imperative Computation (Spring 2018) Frank Pfenning

// walk through array stepping by step amount, moving elements down for (i = unsorted; i >= step && item < a[i-step]; i-=step) { a[i] = a[i-step];

Quicksort. The divide-and-conquer strategy is used in quicksort. Below the recursion step is described:

Sorting (I) Hwansoo Han

9/10/12. Outline. Part 5. Computational Complexity (2) Examples. (revisit) Properties of Growth-rate functions(1/3)

Transcription:

Quicksort (Weiss chapter 8.6)

Recap of before Easter We saw a load of sorting algorithms, including mergesort To mergesort a list: Split the list into two halves Recursively mergesort the two halves Merge the two sorted halves into one This is an instance of divide and conquer Quicksort is also divide and conquer!

Mergesort 1. Split the list into two equal parts 5 3 9 2 8 7 3 2 1 4 5 3 9 2 8 7 3 2 1 4

Mergesort 2. Recursively mergesort the two parts 5 3 9 2 8 7 3 2 1 4 2 3 5 8 9 1 2 3 4 7

Mergesort 3. Merge the two sorted lists together 2 3 5 8 9 1 2 3 4 7 1 2 2 3 3 4 5 7 8 9

Quicksort Pick an element from the array, called the pivot Partition the array: First come all the elements smaller than the pivot, then the pivot, then all the elements greater than the pivot Recursively quicksort the two partitions

Quicksort 5 3 9 2 8 7 3 2 1 4 Say the pivot is 5. Partition the array into: all elements less than 5, then 5, then all elements greater than 5 3 3 2 2 1 4 5 9 8 7 Less than the pivot Greater than the pivot

Quicksort Now recursively quicksort the two partitions! 3 3 2 2 1 4 5 9 8 7 Quicksort Quicksort 1 2 2 3 3 4 5 7 8 9

Pseudocode // call as sort(a, 0, a.length-1); void sort(int[] a, int low, int high) { if (low >= high) return; int pivot = partition(a, low, high); // assume that partition returns the // index where the pivot now is sort(a, low, pivot-1); sort(a, pivot+1, high); } Common optimisation: switch to insertion sort when the input array is small

Complexity of quicksort In the best case, partitioning splits an array of size n into two halves of size n/2: n n/2 n/2

Complexity of quicksort The recursive calls will split these arrays into four arrays of size n/4: n n/2 n/2 n/4 n/4 n/4 n/4

n n/2 n/2 Total time is O(n log n)! n/4 n/4 n/4 n/4 log n levels n/8 n/8 n/8 n/8 n/8 n/8 n/8 n/8 O(n) time per level

Complexity of quicksort But that's the best case! In the worst case, everything is greater than the pivot (say) The recursive call has size n-1 Which in turn recurses with size n-2, etc. Amount of time spent in partitioning: n + (n-1) + (n-2) + + 1 = O(n 2 )

n n-1 Total time is O(n 2 )! n-2 n levels n-3 O(n) time per level

Worst cases When we pick the first element as the pivot, we get this worst case for: Sorted arrays Reverse-sorted arrays

Complexity of quicksort Quicksort works well when the pivot splits the array into roughly equal parts Median-of-three: pick first, middle and last element of the array and pick the median of those three Pick pivot at random: gives O(n log n) expected (probabilistic) complexity Introsort: detect when we get into the O(n 2 ) case and switch to a different algorithm (e.g. heapsort)

Partitioning algorithm 1. Pick a pivot (here 5) 5 3 9 2 8 7 3 2 1 4

Partitioning algorithm 2. Set two indexes, low and high 5 3 9 2 8 7 3 2 1 4 low high Idea: everything to the left of low is less than the pivot (coloured yellow), everything to the right of high is greater than the pivot (green)

Partitioning algorithm 3. Move low right until you find something greater than the pivot 5 3 9 2 8 7 3 2 1 4 low high

Partitioning algorithm 3. Move low right until you find something greater or equal to the pivot 5 3 9 2 8 7 3 2 1 4 low high while (a[low] < pivot) low++;

Partitioning algorithm 3. Move low right until you find something greater than the pivot 5 3 9 2 8 7 3 2 1 4 low high while (a[low] < pivot) low++;

Partitioning algorithm 3. Move high left until you find something less than the pivot 5 3 9 2 8 7 3 2 1 4 low high while (a[high] < pivot) high--;

Partitioning algorithm 4. Swap them! 5 3 4 2 8 7 3 2 1 9 low swap(a[low], a[high]); high

Partitioning algorithm 5. Advance low and high and repeat 5 3 4 2 8 7 3 2 1 9 low low++; high--; high

Partitioning algorithm 5. Advance low and high and repeat 5 3 4 2 8 7 3 2 1 9 low high while (a[low] < pivot) low++;

Partitioning algorithm 5. Advance low and high and repeat 5 3 4 2 8 7 3 2 1 9 low high

Partitioning algorithm 5. Advance low and high and repeat 5 3 4 2 8 7 3 2 1 9 low high while (a[high] < pivot) high++;

Partitioning algorithm 5. Advance low and high and repeat 5 3 4 2 1 7 3 2 8 9 low swap(a[low], a[high]); high

Partitioning algorithm 5. Advance low and high and repeat 5 3 4 2 1 7 3 2 8 9 low++; high--; low high

Partitioning algorithm 5. Advance low and high and repeat 5 3 4 2 1 7 3 2 8 9 low high

Partitioning algorithm 5. Advance low and high and repeat 5 3 4 2 1 7 3 2 8 9 low high

Partitioning algorithm 5. Advance low and high and repeat 5 3 4 2 1 2 3 7 8 9 low high

Partitioning algorithm 5. Advance low and high and repeat 5 3 4 2 1 2 3 7 8 9 low high

Partitioning algorithm 5. Advance low and high and repeat 5 3 4 2 1 2 3 7 8 9 low high

Partitioning algorithm 6. When low and high have crossed, we are finished! 5 3 4 2 1 2 3 7 8 9 But the pivot is in the wrong place. low high

Partitioning algorithm 7. Last step: swap pivot with high 3 3 4 2 1 2 5 7 8 9 low high

Details 1. What to do if we want to use a different element (not the first) for the pivot? Swap the pivot with the first element before starting partitioning!

Details 2. What happens if the array contains many duplicates? Notice that we only advance a[low] as long as a[low] < pivot If a[low] == pivot we stop, same for a[high] If the array contains just one element over and over again, low and high will advance at the same rate Hence we get equal-sized partitions

Pivot Which pivot should we pick? First element: gives O(n 2 ) behaviour for alreadysorted lists Median-of-three: pick first, middle and last element of the array and pick the median of those three Pick pivot at random: gives O(n log n) expected (probabilistic) complexity

Quicksort Typically the fastest sorting algorithm......but very sensitive to details! Must choose a good pivot to avoid O(n 2 ) case Must take care with duplicates Switch to insertion sort for small arrays to get better constant factors

Mergesort vs quicksort Quicksort: In-place O(n log n) but O(n 2 ) if you are not careful Works on arrays only (random access) Compared to mergesort: Not in-place O(n log n) Only requires sequential access to the list this makes it good in functional programming Both the best in their fields! Quicksort best imperative algorithm Mergesort best functional algorithm

Complexity of recursive functions (Weiss 7.5)

Calculating complexity Let T(n) be the time mergesort takes on a list of size n Mergesort does O(n) work to split the list in two, two recursive calls of size n/2 and O(n) work to merge the two halves together, so... T(n) = O(n) + 2T(n/2) Time to sort a list of size n Linear amount of time spent in splitting + merging Plus two recursive calls of size n/2

Calculating complexity Procedure for calculating complexity of a recursive algorithm: Write down a recurrence relation e.g. T(n) = O(n) + 2T(n/2) Solve the recurrence relation to get a formula for T(n) (difficult!) There isn't a general way of solving any recurrence relation we'll just see a few families of them

Approach 1: draw a diagram

n T(n) n/2 n/2 Total time is O(n log n)! n/4 n/4 n/4 n/4 2T(n/2) O(log n) levels 4T(n/4) n/8 n/8 n/8 n/8 n/8 n/8 n/8 n/8 8T(n/8) O(n) time per level

Another example: T(n) = O(1) + 2T(n-1)

1 T(n) 1 1 1 1 1 1 2T(n-1) O(n) levels 4T(n-2) 1 1 1 1 1 1 1 1 8T(n-3) amount of work doubles at each level

1 T(n) 1 1 Total time is O(2 n )! 1 1 1 1 2T(n-1) O(n) levels 4T(n-2) 1 1 1 1 1 1 1 1 8T(n-3) amount of work doubles at each level

This approach Good for building an intuition Maybe a bit error-prone Approach 2: expand out the definition Example: solving T(n) = O(1) + T(n-1)

Expanding out recurrence relations T(n) = 1 + T(n-1) = 2 + T(n-2) = 3 + T(n-3) T(0) is a constant, so O(1) = = n + T(0) = O(n)

Another example: T(n) = O(n) + T(n-1) T(n) = n + T(n-1) = n + (n-1) + T(n-2) = n + (n-1) + (n-2) + T(n-3) = = n + (n-1) + (n-2) + + 1 + T(0) = n(n+1) / 2 + T(0) = O(n 2 )

Another example: T(n) = O(1) + T(n/2) T(n) = 1 + T(n/2) = 2 + T(n/4) = 3 + T(n/8) = = log n + T(1) = O(log n)

Another example: T(n) = O(n) + T(n/2) T(n) = n + T(n/2): T(n) = n + T(n/2) = n + n/2 + T(n/4) = n + n/2 + n/4 + T(n/8) = = n + n/2 + n/4 + < 2n = O(n)

Functions that recurse once T(n) = O(1) + T(n-1): T(n) = O(n) T(n) = O(n) + T(n-1): T(n) = O(n 2 ) T(n) = O(1) + T(n/2): T(n) = O(log n) T(n) = O(n) + T(n/2): T(n) = O(n) An almost-rule-of-thumb: Solution is maximum recursion depth times amount of work in one call (except that this rule of thumb would give O(n log n) for the last case)

Divide-and-conquer algorithms T(n) = O(n) + 2T(n/2): T(n) = O(n log n) This is mergesort! There is a nice proof in the book (theorem 7.4). T(n) = 2T(n-1): T(n) = O(2 n ) Because 2 n recursive calls of depth n Other cases: master theorem (Wikipedia) or theorem 7.5 from book Kind of fiddly best to just look it up if you need it

Complexity of recursive functions Basic idea recurrence relations Easy enough to write down, hard to solve One technique: expand out the recurrence and see what happens Another rule of thumb: multiply work done per level with number of levels Drawing a diagram (like for quicksort) can help! Master theorem for divide and conquer Luckily, in practice you come across the same few recurrence relations, so you just need to know how to solve those