關於 折半尋找 while 條件 < , <=,折半尋找while條件

來源:互聯網
上載者:User

關於 折半尋找 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。
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.