#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int binarySearch(int list[], int n, int key, int *count) {
int low = 0, high = n - 1, num = 0;
int t = (low + high) / 2;
while (low <= high) {
if (list[t] == key) {
num++;
(*count) = num;
return t;
} else if (list[t] < key) {
num++;
low = t + 1;
t = (low + high) / 2;
} else {
num++;
high = t - 1;
t = (low + high) / 2;
}
}
(*count) = num;
return -1;
}
void sort(int list[], int n) {
int i, j, t;
for (i = 1; i < n; i++) {
for (j = 0; j < n - i; j++) {
if (list[j] > list[j + 1]) {
t = list[j + 1];
list[j + 1] = list[j];
list[j] = t;
}
}
}
}
int main() {
int i, n, key, count = 0;
int a[MAX];
while (scanf("%d", &n) == 1) {
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
sort(a, n);
scanf("%d", &key);
if ((i = binarySearch(a, n, key, &count)) >= 0) {
printf("%d [%d]\n", i + 1, count);
} else {
printf("no [%d]\n", count);
}
}
return 0;
}
标签:count,折中,int,scanf,list,low,key,排序
From: https://blog.51cto.com/u_16030624/6443272