编写一个程序解决选择问题

数据结构与算法分析——c语言描述 练习1.1


方法是书上的,先读入k个数,然后后面的假如大于k就把最后一个数挤出去,用了二分查找。


#include<stdio.h>
#define MAXN 1000
int arri[MAXN];

void intsert( int x, int N) {
	int low, mid, high;
	low = 0; high = N - 1;
	while (low <= high) {
		mid = (low + high)/2;
		if (arri[mid] < x) {
			high = mid- 1;
		}
		else if (arri[mid]>x)
			low = mid + 1;
	}
	while (arri[low] > x)
		low++;
	for (int i = N - 1; i > low; i--) {
		arri[i] = arri[i - 1];
	}
	arri[low] = x;
}

int main() {
	int k,n;
	scanf("%d", &n);
	k = n / 2;
	for (int i = 0; i < k; i++) {
		scanf("%d", &arri[i]);
	}
	int flag=1;
	while (flag == 1)
	{
		flag = 0;
		for (int i = 0; i < k - 1; i++) {
			if (arri[i] < arri[i + 1]) {
				flag = 1;
				int t = arri[i + 1];
				arri[i + 1] = arri[i];
				arri[i] = t;
			}
		}
	}
	for (int i = k; i < n; i++){
		int t;
		scanf("%d", &t);
		if (t > arri[k - 1])
			intsert(t, k);
	}
	printf("%d", arri[k - 1]);
}


你可能感兴趣的:(答案,数据结构与算法分析c语言描述)