我按照quickSelect来理解和实现 quickSelect 算法。我不确定的一件事是:他们为什么这样做k-pivot
并且pivot-first+1
。
尽管我的实现与此链接完全相同,但它不起作用。
#include <stdio.h>
#include <string.h>
#define DEBUG 1
#define debug(fmt, ...)\
do{\
if(DEBUG)\
fprintf(stdout, "%s(%d) : " fmt "\n", __FUNCTION__, __LINE__, __VA_ARGS__);\
}while(0)
#define swap(a, b)\
do{\
if(a != b) {\
a = a ^ b;\
b = a ^ b;\
a = a ^ b;\
}\
}while(0)
int
partition(int *a, int low, int high)
{
int i = low, j = high;
int pivot = a[i];
i++;
while(i < j)
{
while(pivot >= a[i])
i++;
while(pivot < a[j])
j--;
if(i < j)
swap(a[i], a[j]);
}
swap(a[low], a[j]);
return j;
}
int
quick_select(int *a, int start, int end, int k)
{
if(start < end)
{
int pivot = partition(a, start, end);
if(k < (pivot - start + 1))
return quick_select(a, start, pivot, k);
else if( k > (pivot - start + 1))
return quick_select(a, pivot+1, end, k - pivot);
else
return a[pivot];
}
}
int
main()
{
int a[100], k, n;
int ret, i;
while(1)
{
printf("# of items : ");
scanf("%d", &n);
printf("Items : ");
for(i = 0; i<n; i++)
scanf("%d", &a[i]);
printf("<k> : ");
scanf("%d", &k);
ret = quick_select(a, 0, n-1, k);
printf("[%d] smallest element = [%d]\n", k, ret);
}
return 0;
}
输出 :
./a.out
# of items : 10
Items : 1 2 3 4 5 6 7 8 9 10
<k> : 9
[9] smallest element = [32767]