關於 折半尋找 while 條件 < , <=,折半尋找while條件
int bin_search(int a[],int len,int key)
{
int low=0;
int high=len-1;
while(low<=high) //若為low<high; e.g.1,2,3,4,5 如果search 5 ,最終 low==high=4; 而循
//體 不執行。
{
int mid=low+(high-low)/2;
if(a[mid]==key) return mid;
else
if(a[mid]<key)
low=mid+1;
else
high=mid-1;
}
if(low>high)
return -1;
}
對於C++折半法尋找的問題
//輸入代碼有點邏輯問題
//排序少了個減一
//尋找少了個break且
//while 迴圈條件反了。
#include <iostream.h>
void Renew(int A[]);
int BinarySearch(int A[],int x,int n);
int main()
{
int Stu[15];
int i=0;
int scr;
cout<<"Please enter score:"<<endl;
for (i;i<15;i++)//輸入資料並查錯
{
do
{
cin>>scr;
if (scr>=0&&scr<=100)
{
Stu[i]=scr;
}
else
cout<<"輸入錯誤,請重新輸入"<<endl;
}while(scr<0||scr>100);//here
}
Renew(Stu);//調用排序
//輸出排序結果
for (i=0;i<15;i++)
{
cout<<"NewScore["<<i<<"]="<<Stu[i]<<endl;
}
//調用折半法尋找
int x;
cout<<"Please enter the score in your mind:"<<endl;
cin>>x;
cout<<"The Score "<<x<<" is the "<<BinarySearch(Stu,x,15)<<endl;
return 0;
}
void Renew(int A[])//排序函數
{
int i,j,temp;
for(i=0;i<15-1;i++)//here
{
for (j=i+1;j<15;j++)
{
if (A[i]<A[j])
{
temp=A[i];
A[i]=A[j];
A[j]=temp;
}
}
}
}
int BinarySearch(int A[],int x,int n)//折半法尋找
{
int left=0;
int right=n-1;
int sum=-1;
do
{
int middle = (left+right)/2;
if (x==A[middle])
{
sum = middle;break;//here
}
else if (x>A[middle])
right=middle-1;
else left=middle+1;
}while (left <= right);//here
return sum;
}...餘下全文>>
折半尋找法的結束條件是什?
迴圈的條件是low<=high,結束的條件就是low>high。