good article————K’th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)

这是本人在研究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.

// C++ implementation of randomized quickSelect

#include<iostream>

#include<climits>

#include<cstdlib>

using
namespace
std;

int
randomPartition(int
arr[], int
l, int
r);

// This function returns k‘th smallest element in arr[l..r] using

// QuickSort based method.  ASSUMPTION: ALL ELEMENTS IN ARR[] ARE DISTINCT

int
kthSmallest(int
arr[], int
l, int
r, int
k)

{

    // 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

        int
pos = randomPartition(arr, l, r);

        // If position is same as k

        if
(pos-l == k-1)

            return
arr[pos];

        if
(pos-l > k-1)  // If position is more, recur for left subarray

            return
kthSmallest(arr, l, pos-1, k);

        // Else recur for right subarray

        return
kthSmallest(arr, pos+1, r, k-pos+l-1);

    }

    // If k is more than number of elements in array

    return
INT_MAX;

}

void
swap(int
*a, int
*b)

{

    int
temp = *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()

int
partition(int
arr[], int
l, int
r)

{

    int
x = arr[r], i = l;

    for
(int
j = l; j <= r - 1; j++)

    {

        if
(arr[j] <= x)

        {

            swap(&arr[i], &arr[j]);

            i++;

        }

    }

    swap(&arr[i], &arr[r]);

    return
i;

}

// Picks a random pivot element between l and r and partitions

// arr[l..r] arount the randomly picked element using partition()

int
randomPartition(int
arr[], int
l, int
r)

{

    int
n = r-l+1;

    int
pivot = rand() % n;

    swap(&arr[l + pivot], &arr[r]);

    return
partition(arr, l, r);

}

// Driver program to test above methods

int
main()

{

    int
arr[] = {12, 3, 5, 7, 4, 19, 26};

    int
n = sizeof(arr)/sizeof(arr[0]), k = 3;

    cout <<
"K‘th smallest element is "
<< kthSmallest(arr, 0, n-1, k);

    return
0;

}

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:

时间: 2024-08-09 21:12:22

good article————K’th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)的相关文章

【LeetCode-面试算法经典-Java实现】【215-Kth Largest Element in an Array(数组中第K大的数)】

[215-Kth Largest Element in an Array(数组中第K大的数)] [LeetCode-面试算法经典-Java实现][所有题目目录索引] 代码下载[https://github.com/Wang-Jun-Chao] 原题 Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth d

网易2016 实习研发工程师 [编程题]寻找第K大 and leetcode 215. Kth Largest Element in an Array

传送门 有一个整数数组,请你根据快速排序的思路,找出数组中第K大的数. 给定一个整数数组a,同时给定它的大小n和要找的K(K在1到n之间),请返回第K大的数,保证答案存在. 测试样例: [1,3,5,2,2],5,3 返回:2 note: 注意手写快排的时候: while(i < j) { while(j > i && a[j] > a[left]) j--; while(i < j && a[i] <= a[left]) i++; if(i

LeetCode | 0215. Kth Largest Element in an Array数组中的第K个最大元素【Python】

LeetCode 0215. Kth Largest Element in an Array数组中的第K个最大元素[Medium][Python][快排][堆] Problem LeetCode Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Example 1:

leetcode Kth Largest Element in an Array

题目连接 https://leetcode.com/problems/kth-largest-element-in-an-array/ Kth Largest Element in an Array Description Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct eleme

LeetCode OJ 215. Kth Largest Element in an Array 堆排序求解

题目链接:https://leetcode.com/problems/kth-largest-element-in-an-array/ 215. Kth Largest Element in an Array My Submissions Question Total Accepted: 43442 Total Submissions: 136063 Difficulty: Medium Find the kth largest element in an unsorted array. Not

Leetcode题解(3):L215/Kth Largest Element in an Array

L215: Kth Largest Element in an Array Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. For example, Given [3,2,1,5,6,4] and k = 2, return 5. Note: You may as

堆排序 &amp;&amp; Kth Largest Element in an Array

堆排序 堆节点的访问 通常堆是通过一维数组来实现的.在数组起始位置为0的情形中: 父节点i的左子节点在位置(2*i+1); 父节点i的右子节点在位置(2*i+2); 子节点i的父节点在位置floor((i-1)/2); 堆的操作 在堆的数据结构中,堆中的最大值总是位于根节点(在优先队列中使用堆的话堆中的最小值位于根节点).堆中定义以下几种操作: 最大堆调整(Max_Heapify):将堆的末端子节点作调整,使得子节点永远小于父节点 创建最大堆(Build_Max_Heap):将堆所有数据重新排序

【LeetCode】215. Kth Largest Element in an Array (2 solutions)

Kth Largest Element in an Array Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. For example,Given [3,2,1,5,6,4] and k = 2, return 5. Note: You may assume k

leetcode_215题——Kth Largest Element in an Array(堆排序)

Kth Largest Element in an Array Total Accepted: 13165 Total Submissions: 48240My Submissions Question Solution Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct elemen