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

more robust and easier to understand. #892

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
68 changes: 36 additions & 32 deletions Algorithms/yourname.github/Quick_Select_Algorithm.cpp
Original file line number Diff line number Diff line change
@@ -1,42 +1,46 @@
#include<bits/stdc++.h>
#include <bits/stdc++.h>
using namespace std;

int partition(int a[],int s,int e)
{
int ind=s;
int pivot=a[e];

for(int i=s;i<e;i++)
{
if(a[i]<=pivot)
swap(a[i],a[ind++]);
int partition(int a[], int s, int e) {
int pivot = a[e];
int ind = s;
for (int i = s; i < e; i++) {
if (a[i] <= pivot) {
swap(a[i], a[ind]);
ind++;
}
}

swap(a[e],a[ind]);

swap(a[e], a[ind]);
return ind;
}

int find_kth_smallest(int a[],int s,int e,int k)
{
int pind=partition(a,s,e);

if(k>pind)
return find_kth_smallest(a,pind+1,e,k);
else if(k<pind)
return find_kth_smallest(a,s,pind-1,k);
else
return a[pind];
int find_kth_smallest(int a[], int s, int e, int k) {
if (s <= e) {
int pind = partition(a, s, e);
if (pind == k) {
return a[pind];
} else if (pind > k) {
return find_kth_smallest(a, s, pind - 1, k);
} else {
return find_kth_smallest(a, pind + 1, e, k);
}
}
return INT_MAX; // Return a large value if k is out of bounds
}

int main()
{
int main() {
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
int k;
cin>>k;
cout<<find_kth_smallest(a,0,n-1,k-1);
}
cin >> k;
if (k > 0 && k <= n) {
cout << find_kth_smallest(a.data(), 0, n - 1, k - 1) << endl;
} else {
cout << "Invalid value of k" << endl;
}
return 0;
}