- 论坛徽章:
- 1
|
任给一组数字(整数), 如何快速求得中间值.
基于快速排序的不完全排序实现
- #include <time.h>;
- void swap(int *ary, int i, int j)
- {
- int t;
- t = ary[i]; ary[i] = ary[j]; ary[j] = t;
- }
- int middle(int *ary, int num)
- {
- int low, high, elem, begin, end;
- begin = 0; end = num;
- while( begin < end ) {
- elem = ary[begin];
- low = begin;
- high = end;
- while(ary[++low] < elem && low < high);
- while(ary[--high] >; elem && high >;= low);
- while(low < high) {
- swap(ary, low, high);
- while(ary[++low] < elem && low < high);
- while(ary[--high] >; elem && high >;= low);
- }
- swap(ary, begin, high);
- if(high >; num / 2)
- end = high;
- else if(high < num / 2)
- begin = high + 1;
- else
- break;
- }
- return ary[high];
- }
- int main(int argc, char *argv[])
- {
- int i, ary[100], num, result;
- num = atoi(argv[1]);
- srand(time(NULL));
- printf("Arry :");
- for(i = 0; i < num; i++) {
- ary[i] = rand() % 100;
- printf("%d ", ary[i]);
- }
- printf("\n");
- result = middle(ary, num);
- printf("Last Arry :");
- for(i = 0; i < num; i++)
- printf("%d ", ary[i]);
- printf("\n");
- printf("Result :%d\n", result);
- }
复制代码 |
|