二分法 搜尋
(高顯忠, sjgau4311@gmail.com, 2011-10-11 14:40)
1樓
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// ----------------------------------------------
void show_data(int a[], int no)
{
int i;
printf("\n");
for (i=0;i<no;i++) {
printf("%2d, ", a[i]);
}
printf("\n");
system("pause");
}// end of show_data()
// ----------------------------------------------
// swap_int( &a[j], &a[k]);
void swap_int(int *a, int *b)
{
int temp;
temp= *a;
*a= *b;
*b= temp;
}// end of swap_int()
// ----------------------------------------------
int main()
{
srand(time(NULL));
int a[10], no= 10, i, j, k;// a[0] ... a[9]
// generate data
for (i=0;i<no;i++) {
a[i]= rand()%100;
}
show_data(a, no);
// ------------------------------------------
// sort data, by bubble- sort
for (i=0;i<no;i++) {
for (j=0;j<(no-1);j++) {
k= j + 1;
// we hope a[j] <= a[k]
if (a[j] > a[k]) {
swap_int(&a[j], &a[k]);
}
}
}
show_data(a, no);
// ------------------------------------------
// input a number for find
int find;
printf("\n Input a number for search: ");
scanf("%d", &find);
// ------------------------------------------
int low, upper, mid;
low= 0;
upper= no - 1;
while (low <= upper) {// repeat for search
mid= (low + upper)/2;
if (find > a[mid]) {
low= mid + 1;
}
else if (find < a[mid]) {
upper= mid - 1;
}
else {// find == a[mid]
printf("\n , mid= %d, a[mid]= %d, find= %d \n",
mid, a[mid], find);
system("pause");
return 0;
}// end if
}// end while
printf("\n *** no find of search! \n");
system("pause");
return 0;
}// end of main()