问题链接:HDU1157 POJ2338 Who‘s
in the Middle。基础级练习题,用C语言编写程序。
题意简述:输入n,然后输入n个整数,求这n个整数中大小位于中间的数。
问题分析:使用分治法,用求第k大数算法实现。
AC的C语言程序如下:
/* HDU1157 POJ2338 Who's in the Middle */ #include <stdio.h> #define MAXN 10000 int data[MAXN+1]; int split(int a[], int low, int high) { int part_element = a[low]; for (;;) { while (low < high && part_element <= a[high]) high--; if (low >= high) break; a[low++] = a[high]; while (low < high && a[low] <= part_element) low++; if (low >= high) break; a[high--] = a[low]; } a[high] = part_element; return high; } // 非递归选择问题算法程序 int selectmink(int a[], int low, int high, int k) { int middle; for(;;) { middle = split(a, low, high); if(middle == k) return a[k]; else if(middle < k) low = middle+1; else /* if(middle > k) */ high = middle-1; } } int main(void) { int n, ans, i; while(scanf("%d", &n) != EOF) { for(i=0; i<n; i++) scanf("%d", &data[i]); ans = selectmink(data, 0, n - 1, n / 2); printf("%d\n", ans); } return 0; }
HDU1157 POJ2338 Who's in the Middle
时间: 2024-10-29 20:19:19