Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add quickselect.cpp file #201

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions Algorithms/Selection_Algorithms/QuickSelect/quickselect.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,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;
}