Download quick sort easy slides and more Exams Software Engineering in PDF only on Docsity!
Mergesort and Quicksort
Chapter 8
Kruse and Ryba
Sorting algorithms
• Insertion, selection and bubble sort have
quadratic worst-case performance
• The faster comparison based algorithm?
O(nlogn)
• Mergesort and Quicksort
Partitioning - Choice 1
- (^) First n-1 elements into set A, last element set B
- (^) Sort A using this partitioning scheme recursively
- (^) Combine A and B using method Insert() (= insertion
into sorted array)
- (^) Leads to recursive version of InsertionSort()
- (^) Number of comparisons: O(n^2 )
- (^) Best case = n-
- (^) Worst case = (^2)
2
^
n n
c i
n
i
Partitioning - Choice 2
- (^) Put element with largest key in B, remaining elements
in A
- (^) Sort A recursively
- (^) To combine sorted A and B, append B to sorted A
- (^) Use Max() to find largest element recursive SelectionSort()
- (^) Use bubbling process to find and move largest element to right-most position recursive BubbleSort()
- (^) All O(n^2 )
Example
• Partition into lists of size n/
[10, 4, 6, 3]
[10, 4, 6, 3, 8, 2, 5, 7]
[8, 2, 5, 7]
[10, 4] [6, 3]^ [8, 2]^ [5, 7]
[4] [10] [3][6] [2][8] [5][7]
Example Cont’d
• Merge
[3, 4, 6, 10]
[2, 3, 4, 5, 6, 7, 8, 10 ]
[2, 5, 7, 8]
[4, 10] [3, 6]^ [2, 8]^ [5, 7]
[4] [10] [3][6] [2][8] [5][7]
Merge Function
Evaluation
• Recurrence equation:
• Assume n is a power of 2
c 1 if n=
T(n) =
2T(n/2) + c 2 n if n>1, n=2k
Quicksort Algorithm
Given an array of n elements (e.g., integers):
- (^) If array only contains one element, return
- (^) Else
- (^) pick one element to use as pivot.
- (^) Partition elements into two sub-arrays:
- (^) Elements less than or equal to pivot
- (^) Elements greater than pivot
- (^) Quicksort two sub-arrays
- (^) Return results
Example
We are given array of n integers to sort:
Partitioning Array
Given a pivot, partition the elements of the array
such that the resulting array consists of:
- One sub-array that contains elements >= pivot
- Another sub-array that contains elements < pivot
The sub-arrays are stored in the original data array.
Partitioning loops through, swapping elements
below/above pivot.
pivot_index = 0 40 20 10 80 60 50 7 30 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]
too_big_index (^) too_small_index
pivot_index = 0 40 20 10 80 60 50 7 30 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]
too_big_index (^) too_small_index
- While data[too_big_index] <= data[pivot] ++too_big_index
pivot_index = 0 40 20 10 80 60 50 7 30 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]
too_big_index (^) too_small_index
- While data[too_big_index] <= data[pivot] ++too_big_index