二分查找也叫折半查找,原理不用寫了,百度下,這裏給出C語言版本
#include <stdio.h>
#define N 10
void printA(int A[], char n){
int i = 0;
for (i = 0; i < n; i++)
{
printf("%d ", A[i]);
}
printf("\n");
}
void printSearch(int A[], char n, int count, int low, int high){
int i = 0;
printf("第%d次折半,low %d,high %d :", count, low, high);
for (i = 0; i < n; i++)
{
if (low == i)
printf("[");
printf(" %d ", A[i]);
if (high == i)
printf("]");
}
printf("\n");
}
int search_binary(int A[], int n, int Key)
{
//在有序表R[0..n-1]中進行二分查找,成功時返回結點的位置,失敗時返回-1
int low = 0, high = n-1, mid = 0, count = 0;//置當前查找區間上、下界的初值
while(low <= high)
{
//printf("第%d次查找 low:%d mid:%d high:%d\n", ++count, low, mid, high);
if(Key == A[low])
return low;
if(Key == A[high])
return high;
//當前查找區間A[low..high]非空
mid = low + ((high-low)/2); //使用(low+high)/2會有整數溢出的問題
//(問題會出現在當low+high的結果大於表達式結果類型所能表示的最大值時,
//這樣,產生溢出後再/2是不會產生正確結果的,而low+((high-low)/2)不存在這個問題
if(Key == A[mid])
return mid;//查找成功返回
if(A[mid] < Key)
{
low = mid + 1;//繼續在A[mid+1..high]中查找
}
else
{
high = mid - 1;//繼續在A[low..mid-1]中查找
}
printSearch(A, n, ++count, low, high);
}
if(low>high)
return -1;//當low>high時表示所查找區間內沒有結果,查找失敗
}
int main(){
int A[N] = { -10, 0, 1, 5, 7, 24, 31, 58, 59, 99}; //已排序好
int pos = 0;
printf("初始化:");
printA(A, N);
printf("查找1所在位置\n");
pos = search_binary(A, N, 1);
printf("1所在位置是 %d:\n", pos);
printf("查找12所在位置\n");
pos = search_binary(A, N, 12);
printf("12所在位置是 %d:\n", pos);
return 0;
}
運行結果
初始化:-10 0 1 5 7 24 31 58 59 99
查找1所在位置
第1次折半,low 0,high 3 :[ -10 0 1 5 ] 7 24 31 58 59 99
第2次折半,low 2,high 3 : -10 0 [ 1 5 ] 7 24 31 58 59 99
1所在位置是 2:
查找12所在位置
第1次折半,low 5,high 9 : -10 0 1 5 7 [ 24 31 58 59 99 ]
第2次折半,low 5,high 6 : -10 0 1 5 7 [ 24 31 ] 58 59 99
第3次折半,low 5,high 4 : -10 0 1 5 7 ][ 24 31 58 59 99
12所在位置是 -1:
可以看到,第一次查找1的時候,折半了兩次,一次是調整到A[0]=-10和A[3]=5區間,第二次調整到A[2]=1和A[3]=5區間,然後再對比一次就找到了1的位置是2.
同理找12的時候,進行了3次折半,最後沒找到,返回位置-1的報錯。
始於2009-03-30,西理工;更新至2016-06-15,杭州。