线性时间内求数组中的 第k小数

只在快拍的基础上改了一点点 与快速排序算法不同的是,我们关注的并不是元素的左右两边,而仅仅是某一边

#include<iostream>
using namespace std;
int a[100];
int p(int left,int right)
{
    int t,temp=a[left];
    while(left<right)
    {
        while(left<right&&a[left]<=temp)
            left++;
        while(left<right&&a[right]>=temp)
            right--;
    }
    return left;
}


int pai(int low,int high,int m)
{
    int u;
    u=p(low,high);
    if(u==m)
        return a[u];
    else if(u>m)
        return pai(low,u-1,m);
    else return pai(u+1,high,m);
}
    
int main()
{
    int i,j,m,n;
    scanf("%d",&n);
    for(i=1;i<=n;i++)
        scanf("%d",&a[i]);
    scanf("%d",&m);         //在数组a中找第 m小的
    int w=pai(0,n-1,m);
    printf("%d",w);
    return 0;
}

 

posted @ 2013-06-27 21:07  galaxy77  阅读(218)  评论(0编辑  收藏  举报