这是本人在研究leetcode中Median of Two Sorted Arrays一题目的时候看到一篇文章,觉得非常好,其中对快速排序重新实现。
文章来源于http://www.geeksforgeeks.org/这个网站。
We recommend to read following post as a prerequisite of this post.
K’th Smallest/Largest Element in Unsorted Array | Set 1
Given an array and a number k where k is smaller than size of array, we need to find the k’th smallest element in the given array. It is given that ll array elements are distinct.
Examples:
Input: arr[] = {7, 10, 4, 3, 20, 15} k = 3 Output: 7 Input: arr[] = {7, 10, 4, 3, 20, 15} k = 4 Output: 10
We have discussed three different solutions here.
In this post method 4 is discussed which is mainly an extension of method 3 (QuickSelect) discussed in the previouspost.
The idea is to randomly pick a pivot element. To implement randomized partition, we use a random function, rand() to
generate index between l and r, swap the element at randomly generated index with the last element, and finally call the standard partition process which uses last element as pivot.
Following is C++ implementation of above Randomized QuickSelect.
|
Output:
K‘th smallest element is 5
Time Complexity:
The worst case time complexity of the above solution is still O(n2). In worst case, the randomized function may always pick a corner element. The expected time complexity of above randomized QuickSelect is Θ(n), see CLRS
book or MIT
video lecture for proof. The assumption in the analysis is, random number generator is equally likely to generate any number in the input range.
Sources:
MIT
Video Lecture on Order Statistics, Median
Introduction to Algorithms by Clifford Stein, Thomas
H. Cormen, Charles E. Leiserson, Ronald L.
This article is contributed by Shivam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Related Topics:
- K’th Smallest/Largest Element in Unsorted
Array | Set 1 - Time complexity of insertion sort
when there are O(n) inversions? - How to check if two given sets are disjoint?
- Minimum Number of Platforms
Required for a Railway/Bus Station - Find the closest pair from two sorted
arrays - Print all
elements in sorted order from row and column wise sorted matrix - Length of the largest subarray
with contiguous elements | Set 1 - Given an n
x n square matrix, find sum of all sub-squares of size k x k