简体   繁体   中英

Quickselect algorithm to find kth-smallest

I am trying to use quickselect to find the kth smallest number. but when I write code which is exactly same as on https://www.geeksforgeeks.org/kth-smallestlargest-element-unsorted-array/ it give wrong output but when i copy code from GeeksforGeeks it works. I use same header file but it doesn't works.

my code is

   #include <bits/stdc++.h>
using namespace std;
int partition(int arr[],int l,int r);
void swapp(int *a,int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}



int kthsmallest(int arr[],int l,int r,int k)
{
    if(k > 0 && k <= r - l + 1)
    {
        int pos = partition(arr,l,r);

        if(pos-1 == k-1)
        {
            return arr[pos];
        }
        if(pos-1 > k-1)
        {
            return kthsmallest(arr,l,pos-1,k);
        }

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

    return INT_MAX;
}
int partition(int arr[],int l,int r)
{
    int x = arr[r];
    int i = l;
    for(int j = l;j<=r-1;j++)
    {
        if( arr[j] <= x)
        {
            swapp(&arr[i],&arr[j]);
            i++;
        }
    }
    swapp(&arr[i],&arr[r]);
    return i;
}

int main()
{
    int n;
    cin>>n;

    int arr[n];
    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    }

    int k;
    cin>>k;

    cout<<"kth smallest "<<kthsmallest(arr,0,n-1,k);
    return 0;
}

You've mixed "1 (one)" and "l (alphabet L)" throughout your code. If you fix that, it works

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM