這裏是我嘗試實現二進制搜索方法來查找20個數組中的任意整數X並輸出它在數組中出現的次數。我的二進制搜索出錯了嗎?
我的輸出似乎是錯誤的,因爲它輸出1,無論給定的整數出現在數組中多少次。
有人可以幫我解決問題,告訴我我的代碼有什麼問題嗎? (我知道20非常小,線性方法實現起來更簡單,但我使用20來簡化事情)
只是可以肯定,我在輸入imin = 0和imax = 19 我也確定我已經對數組進行了排序。
#include <iostream>
#include <cstdlib>
#include <vector>
using namespace std;
int A[20] = {0};
int x;
int imin;
int imax;
int BinarySearch(int A[], int value, int low, int high, int count) {
if (high < low){
return -1; // not found
}
int mid = low + ((high - low)/2);
if (A[mid] > value){
cout<< A[mid] << " > " << value <<endl;
return BinarySearch(A, value, low, mid-1, count);
}
else if (A[mid] < value){
cout<< A[mid] << " < " << value <<endl;
return BinarySearch(A, value, mid+1, high, count);
}
if (A[mid] == value){
cout<< A[mid] << " = " << value <<endl;
count = count + 1;
}
return count;
}
int main(){
cout<<"Enter 20 integers"<<endl;
for (int i = 0; i < 20;i++){
cin>>A[i];
}
cout<<"Enter the integer x"<<endl;
cin>>x;
cout<<"What is imin?"<<endl;
cin>>imin;
cout<<"What is imax?"<<endl;
cin>>imax;
int temp;
int i;
for (int j = 1; j < 20; j++){
i = j - 1;
temp = A[j];
while ((i>=0) && (A[i] > temp))
{
A[i+1] = A[i];
i=i-1;
}
A[i+1] = temp;
}
int count = BinarySearch(A, x, imin, imax, 0);
cout<<count<<endl;
system("pause");
}
非常感謝
編輯:在一些更正補充。但是我認爲二分查找算法似乎有些問題!
你是不是20點的整數分配內存。 – 2013-04-08 18:00:40
嗨,道歉!我是一個真正的新手。我能麻煩你爲我詳細闡述一下嗎? – 2013-04-08 18:04:14
@CandyMan:'int A [] = {0};'<---這是一個元素的數組,你讀了20個元素。使它成爲int A [20] = {0};'。 – 2013-04-08 18:05:00