北航机试17年01题:数组中值
题目:从一个无序不重复数组中,输出中间的数和它在数组中的次序(从1开始)如果是偶数个元素,则输出两个,奇数则输出中间一个
样例:
输入 | 输出 |
---|---|
1 5 6 4 3 2 7 9 11 | 5 5 |
1 5 6 4 3 2 7 9 11 8 | 5 5 6 6 |
直接上代码
/*
北航机试17年02数组排序:
自定义快速排序
*/
#include<stdio.h>
int nums[100];
void Swap(int i, int j){
int tmp=nums[i];
nums[i]=nums[j];
nums[j]=tmp;
}
//快速排序找基准点
int partition(int low, int high){
int tmp=nums[low];
while(low<high){
while(low<high && nums[high]>=tmp)
high--;
Swap(low, high);
while(low<high && nums[low]<=tmp)
low++;
Swap(low, high);
}
return low;
}
void Qsort(int low, int high){
if(low<high){
int mid=partition(low, high);
Qsort(low, mid-1);
Qsort(mid+1, high);
}
}
int main(){
int size=0;//size为输入元素数
FILE *fp=fopen("e:\\test.txt", "r");
while(fscanf(fp, "%d", &nums[size++])!=EOF);
fclose(fp);
size--; //文件最后一次并没有读取到数字,但是size++ 仍然执行了
Qsort(0, size-1);
int tmp=size/2;
if(size%2 == 1){
printf("%d %d\n", nums[tmp], tmp+1);
}else{
printf("%d %d\n%d %d\n", nums[tmp-1], tmp, nums[tmp], tmp+1);
}
return 0;
}
注:
1. C标准库中并没有algorithm.h, 故需要自定义排序函数
2. 若要引用标准库, 如下:#include<algorithm>
using namespace std;
sort(buf, buf+n, cmp);
其中,cmp为自定义的比较函数,默认为小于函数