#include <stdio.h>
#define N 10
void swap(int *a, int *b){
int tmp = *a;
*a = *b;
*b = tmp;
}
void asort(int *a ,int n){
int i, j;
for(i = 1; i < n;i++){
for( j = 0; j <= n - i - 1; j++){
if(a[j] > a[j + 1]){
swap( &a[j], &a[j + 1]);
}
}
}
}
void printA(int *a, int n){
int i;
for(i = 0; i < n; i++){
printf("[%d]:%d ", i, a[i]);
}
printf("\n");
}
int bSearch(int *a , int n, int key){
int start = 0 ,end = n, mid;
while( start <= end){
mid = (start + end) / 2;
if( a[mid] == key){
return mid;
}
else if(a[mid] > key){
end = mid - 1;
}
else{
start = mid + 1;
}
}
return -1;
}
int main(){
int i, a[N] = {0};
srand(time(NULL));
for(i = 0; i < N; i++){
a[i] = rand() % 100;
}
printA(a, N);
asort(a, N);
printA(a, N);
for(i = 0; i < N; i++){
printf("%d in a[%d]\n", a[i], bSearch(a, N, a[i]));
}
}
[C How To Program] 习题6.35 二分查找
最新推荐文章于 2023-02-21 17:22:20 发布