Download presentation
Presentation is loading. Please wait.
1
CS2420: Lecture 10 Vladimir Kulyukin Computer Science Department Utah State University
2
Outline Sorting Algorithms (Chapter 7)
3
MergeSort Code template void mergeSort(vector &a, vector &tmp, int left, int right) { if ( left < right ) { mid = (left + right)/2; mergeSort(a, tmp, left, mid); mergeSort(a, tmp, mid+1, right); merge(a, tmp, left, mid+1, right); }
4
MergeSort Recurrence Given an array of 1 element, mergeSort runs in constant time. Given an array of N > 1 elements, – mergeSort divides the array into two sub- arrays containing N/2 elements each, – merges the two sub-arrays into the result array of N elements.
5
MergeSort Recurrence
6
We can use substitution or telescoping to solve this recurrence. The recurrence solves to O(nlogn) either way.
7
A Recursion Tree for MergeSort n n/2 n/4 ………………………………………………. ……. 11 11 1 1
8
A Recursion Tree for MergeSort The height of the tree is LogN. Each level of the tree is kN. T(N) = kN*LogN = O(NlogN).
9
Question MergeSort is good, but it does require us to allocate extra storage to merge two arrays into one. Can we sort in place?
10
QuickSort: Sorting in Place N elements are partitioned into three segments: Left, Pivot, and Right. The Pivot segment contains exactly one element. No element in the Left segment is larger than the Pivot. No element in the Right segment is smaller than the Pivot.
11
Quicksort Array A
12
Quicksort Array A Pivot
13
Quicksort Array A Pivot LeftRight
14
Quicksort: Key Insight The keys to the left of the pivot are less than or equal to the pivot. The keys to the right of the pivot are greater than or equal to the pivot. Hence, the left and right segments can be sorted independently and no merge is required.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.