程式碼示例:
#include<stdio.h>
#define N 32
void main()
{
char a[N]="0123456789ABCDEHIJKabcdefijklmn",x;
int front,end,mid,i;
printf("請輸入待查詢的字元x:\n");
scanf("%c",&x);
front=0;end=N-1;
mid=(front+end)/2;
while(front<end&&a[mid]!=x)/*front<end表示查詢區間不為空,a[mid]!=x表示沒找到時執行迴圈,找到後結束迴圈*/
if(a[mid]<x)front=mid+1;
if(a[mid]>x)end=mid-1;
}
if(a[mid]!=x)printf("沒找到。\n");
else printf("找到了,在第%d項裡。\n",mid+1);
程式碼示例:
#include<stdio.h>
#define N 32
void main()
{
char a[N]="0123456789ABCDEHIJKabcdefijklmn",x;
int front,end,mid,i;
printf("請輸入待查詢的字元x:\n");
scanf("%c",&x);
front=0;end=N-1;
mid=(front+end)/2;
while(front<end&&a[mid]!=x)/*front<end表示查詢區間不為空,a[mid]!=x表示沒找到時執行迴圈,找到後結束迴圈*/
{
if(a[mid]<x)front=mid+1;
if(a[mid]>x)end=mid-1;
mid=(front+end)/2;
}
if(a[mid]!=x)printf("沒找到。\n");
else printf("找到了,在第%d項裡。\n",mid+1);
}