线性时间内查找第K小(大)算法

#include<stdio.h> //#define swap(x,y) x=x+y;y=x-y;x=x-y void swap(int *a ,int * b) { int c; c = *a; *a = *b; *b = c; } int partion(int a[],int p,int r) { int i,j; for(i = p,j = p;j<r;++j) { if(a[j] < a[r]) { swap(&a[i],&a[j]); ++i; } } swap(&a[i],&a[r]); return i; } int select(int a[],int p,int r,int k) { int i = partion(a,p,r); int j = i-p+1; if(p == r) return a[p]; if(k == j) return a[i]; else if(k < j) return select(a,p,i-1,k); else return select(a,i+1,r,k-j); } int main() { int a[] = {9,11,0,1,0,7,3,4,8,6,5}; printf(“%d/n”,select(a,0,10,5)); return 0; }

    原文作者:查找算法
    原文地址: https://blog.csdn.net/fuchuangbob/article/details/4133671
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞