1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| #include<stdio.h> #include<stdlib.h> #include<time.h>
int Partition(int*arrayA,int n,int p,int r); int RandomPartition(int* arrayA,int n,int p,int r); int RandomSelect(int* arrayA,int n,int p,int r,int i);
void main() { int arrayA[8]={2,1,3,4,8,6,7,5}; int n=sizeof(arrayA)/sizeof(int); int p=0; int r=7; int i=4; int result=0; result=RandomSelect(arrayA,n,p,r,i); printf("数组中第%d小的数是%d\n",i,result);
}
int Partition(int*arrayA,int n,int p,int r) { int x=arrayA[r]; int i=p-1; int temp=0; for(int j=p;j<=r-1;j++) { if(arrayA[j]<=x) { i++; temp=arrayA[i]; arrayA[i]=arrayA[j]; arrayA[j]=temp; } } temp=arrayA[i+1]; arrayA[i+1]=arrayA[r]; arrayA[r]=temp;
return i+1; }
int RandomPartition(int* arrayA,int n,int p,int r) { int suiji=0; srand(time(0)); suiji=rand()%(r-p)+p; printf("suiji=%d\n",suiji); int temp=0; temp=arrayA[r]; arrayA[r]=arrayA[suiji]; arrayA[suiji]=temp;
return Partition(arrayA,n,p,r); }
int RandomSelect(int* arrayA,int n,int p,int r,int i) { int q=0; if(p==r) return arrayA[p];
for(int j=p;j<=r;j++) printf("%d ",arrayA[j]); printf("\n"); q=RandomPartition(arrayA,n,p,r); printf("gaihou:\n"); for(int j=p;j<=r;j++) printf("%d ",arrayA[j]); printf("\n\n");
int k=q-p+1; if(i==k) return arrayA[q]; else if(i<k) return RandomSelect(arrayA,n,p,q-1,i); else return RandomSelect(arrayA,n,q+1,r,i-k);
}
|