Download presentation
Presentation is loading. Please wait.
1
CSCE-221 Selection Emil Thomas 03/07/19
Based on Slides by Prof. Scott Schafer
2
The Selection Problem Given an integer k and n elements x1, x2, …, xn, taken from a total order, find the kth smallest element in this set. Also called order statistics, ith order statistic is ith smallest element Minimum - k=1 - 1st order statistic Maximum - k=n - nth order statistic Median - k=n/2 etc
3
The Selection Problem Naïve solution - SORT!
we can sort the set in O(n log n) time and then index the k-th element. Can we solve the selection problem faster? k=3
4
Quick-Select Quick-select is a randomized selection algorithm based on the prune-and-search paradigm: Prune: pick a random element x (called pivot) and partition S into L elements less than x E elements equal x G elements greater than x Search: depending on k, either answer is in E, or we need to recur on either L or G Note: Partition same as Quicksort x x L G E k > |L|+|E| k’ = k - |L| - |E| k < |L| |L| < k < |L|+|E| (done)
5
In-Place Partitioning
Perform the partition using two indices to split S into two subarrays L and E&G (L:Less, E&G: Equal&Greater) Repeat until l and r cross: Scan l to the right until finding an element > x. Scan r to the left until finding an element < x. Swap elements at indices l and r l r (pivot = 6) l r
6
In-Place Partition PseudoCode
//This Algo uses the last element as pivot Algorithm q = inPlacePartition(S, first, last) Input: sequence Array S, Starting index first, and ending index last Output: Returns an index q such that S[first .. q] <= S[q + 1, …last] Code: pivot S[last] l first – 1 //l is incremented below r last // start from end leaving pivot while (TRUE) { do {l++} while(S[l] < pivot) do {r--} while (pivot < =S[r]); if (l >= r) { return r; } swap(S, l, r); q = inPlacePartition(S, first, last) returns the index q such that L= S[first … q] E&G = S[q+1 … last]
7
Quick-Select InLabDemo&Discussion
8
Quick-Select Visualization
An execution of quick-select can be visualized by a recursion path Each node represents a recursive call of quick-select, and stores k and the remaining sequence k=5, S=( ) k=2, S=( ) k=2, S=( ) k=1, S=( ) Expected running time is O(n) 5
9
Quick-Select PseudoCode
//Input: Array S[first .. last] and the rank(k) //Output: returns the kth smallest element in S Quick_select(S, first, last, k) { If (first == last) //Base case :One element array return S[first]; q = inPlacePartition(S, first, last); L_Size = q – first + 1 //Size of the L array If (k <= L_Size) { return Quick_select(S, first, q, k); //The L array } else return Quick_select(S, q+1, last, k - L_size) //E&G array }
10
Exercise & Survey Survey: on eCampus
11
References
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.