1.问题
求第K小元素。
2.解析
3.设计
4.分析
5.源代码
int Partition( int a[], int start, int end, int pivot ){
int target = a[pivot];
int low = start, high = end;
a[pivot] = a[low];
while ( high > low ){
for ( ; a[high] <= target && high > low; ) {
high--;
}
a[low] = a[high];
for ( ; a[low] >= target && high > low; ) {
low++;
}
a[high] = a[low];
}
a[low] = target;
return low;
}
int Select( int a[], int left, int right, int k ){//求第n-K+1大的数
if ( right - left < 0 || left < 0 || k < 0 || a == NULL ){
return -1;
}
if ( left == right || k == 0 ){
return left;
}
int min, i, kth;
if ( right - left < k ) {//k比数组下标小1, 当数组覆盖范围<k时候,直接返回里面最小的一个数字
min = a[ kth=left ];
i = left+1;
for ( ; i <= right; i++ ){
if( a[i] < min ){ //输出最小的一个,它是第kth大的数
min = a[ kth=i ];
}
}
}
else{
i = Partition( a, left, right, left+k-1 ); //快排
if ( k-1 < i-left ) {//k比数组下标小1
kth = Select( a, left, i-1, k );
}
else if ( k-1 == i-left ){
kth = i;
}
else { //k+1 > i-left
kth = Select( a, i+1, right, k-(i-left+1) );
}
}
return kth;
}