Good article ———— K ' th smallest/largest Element in unsorted Array | Set 2 (expected Linear time)

Source: Internet
Author: User

This is my study leetcode in Median of two Sorted Arrays A topic when I saw an article, feel very good, which on the quick sort of re-implementation.

The article originates from the http://www.geeksforgeeks.org/website.

We recommend to read following post as a prerequisite of the this post.

K ' th smallest/largest Element in unsorted Array | Set 1


Given an array and a number k where k are smaller than size of array, we need to find the k ' th smallest element in the give N Array. It is given, that ll, array elements is distinct.

Examples:

Input:arr[] = {7, ten, 4, 3,       4} k = 3output:7input:arr[] = {7,,, 3, ten}       k = 4output:10

We have discussed three different solutions here.

In this post Method 4 are discussed which is mainly a extension of Method 3 (Quickselect) discussed in the previous post. The idea was 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 a s pivot.

Following is C + + implementation of above randomized quickselect.

// C++ implementation of randomized quickSelect#include<iostream>#include<climits>#include<cstdlib>usingnamespace std;intrandomPartition(intarr[], intl, intr); // This function returns k‘th smallest element in arr[l..r] using// QuickSort based method.  ASSUMPTION: ALL ELEMENTS IN ARR[] ARE DISTINCTintkthSmallest(intarr[], intl, intr, intk){    // If k is smaller than number of elements in array    if(k > 0 && k <= r - l + 1)    {        // Partition the array around a random element and        // get position of pivot element in sorted array        intpos = randomPartition(arr, l, r);        // If position is same as k        if(pos-l == k-1)            returnarr[pos];        if(pos-l > k-1)  // If position is more, recur for left subarray            returnkthSmallest(arr, l, pos-1, k);        // Else recur for right subarray        returnkthSmallest(arr, pos+1, r, k-pos+l-1);    }    // If k is more than number of elements in array    returnINT_MAX;}voidswap(int*a, int*b){    inttemp = *a;    *a = *b;    *b = temp;}// Standard partition process of QuickSort().  It considers the last// element as pivot and moves all smaller element to left of it and// greater elements to right. This function is used by randomPartition()intpartition(intarr[], intl, intr){    intx = arr[r], i = l;    for(intj = l; j <= r - 1; j++)    {        if(arr[j] <= x)        {            swap(&arr[i], &arr[j]);            i++;        }    }    swap(&arr[i], &arr[r]);    returni;}// Picks a random pivot element between l and r and partitions// arr[l..r] arount the randomly picked element using partition()intrandomPartition(intarr[], intl, intr){    intn = r-l+1;    intpivot = rand() % n;    swap(&arr[l + pivot], &arr[r]);    returnpartition(arr, l, r);}// Driver program to test above methodsintmain(){    intarr[] = {12, 3, 5, 7, 4, 19, 26};    intn = sizeof(arr)/sizeof(arr[0]), k = 3;    cout <<"K‘th smallest element is " << kthSmallest(arr, 0, n-1, k);    return0;}

Output:

Time complexity:
The worst case time complexity of the above solution is still O (N2). In worst case, the randomized function is 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 are, the 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 was contributed by Shivam. Please write comments if your find anything incorrect, or you want to share more information about the topic discussed Abov E

         Related Topics:
    • K ' th smallest/largest Element in unsorted Array | Set 1
    • Time complexity of insertion sort when there is O (n) inversions?
    • How to check if given sets is disjoint?
    • Minimum number of platforms Required for a Railway/bus station
    • Find the closest pair from 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

Good article ———— K ' th smallest/largest Element in unsorted Array | Set 2 (expected Linear time)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.