Skip to content

Instantly share code, notes, and snippets.

@piyush01123
Last active February 17, 2023 19:02
Show Gist options
  • Save piyush01123/210e1f3cd8c9af485e07ec7fb6fe2f11 to your computer and use it in GitHub Desktop.
Save piyush01123/210e1f3cd8c9af485e07ec7fb6fe2f11 to your computer and use it in GitHub Desktop.
QuickSelect implementation
#include <bits/stdc++.h>
using namespace std;
int randGen (int i) {srand(time(0)); return rand()%i;}
int partition(int A[], int lo, int hi)
{
int pivot = A[hi];
int i = lo-1;
for (int j=lo; j<=hi; j++)
{
if (A[j]>pivot) continue;
i ++;
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
return i;
}
int quickSelect(int A[], int lo, int hi, int K)
{
if (K<1 || K>hi-lo+1) return -1;
int pi = partition(A, lo, hi);
if (pi-lo+1 == K) return A[pi];
else if (pi-lo+1 < K) return quickSelect(A, pi+1, hi, K-pi+lo-1);
return quickSelect(A, lo, pi-1, K);
}
int main()
{
int A[] = {1,2,3,4,5,6,7};
int n = sizeof(A)/sizeof(int);
random_shuffle(A, A+n, randGen);
cout << " Input:";
for (int i=0; i<n; i++)cout<<A[i]<<','; cout<<endl;
int kth_element = quickSelect(A, 0, n-1, 3);
cout << " Output:";
for (int i=0; i<n; i++)cout<<A[i]<<','; cout<<endl;
cout<< " 3rd item:"<<kth_element<<endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment