forked from coder2hacker/Explore-open-source
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuick Select Algorithm in C++.cpp
65 lines (57 loc) · 1.54 KB
/
Quick Select Algorithm in C++.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// CPP program for implementation of QuickSelect
#include <bits/stdc++.h>
using namespace std;
// 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
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;
}
// 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 last
// element and get position of pivot
// element in sorted array
int index = partition(arr, l, r);
// If position is same as k
if (index - l == k - 1)
return arr[index];
// If position is more, recur
// for left subarray
if (index - l > k - 1)
return kthSmallest(arr, l, index - 1, k);
// Else recur for right subarray
return kthSmallest(arr, index + 1, r,
k - index + l - 1);
}
// If k is more than number of
// elements in array
return INT_MAX;
}
// Driver program to test above methods
int main()
{
int arr[] = { 10, 4, 5, 8, 6, 11, 26 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3;
cout << "K-th smallest element is "
<< kthSmallest(arr, 0, n - 1, k);
return 0;
}