在頂部列出的binary_search函數遇到問題。不知道該去哪裏。我對二進制搜索不太熟悉。二進制搜索功能的問題
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
void get_input(ifstream& fin, int a[], int size, int & array_size);
void binary_search (int a[], int & array_size)
{
cout << "Please enter the element you would like to search for \n";
int element;
cin >> element;
int lastindex=array_size-1, startindex=0;
while (startindex <= lastindex)
{
int midindex=(array_size/2);
if(element > a[midindex])
{
startindex=midindex;
}
else if (element < a[midindex])
{
lastindex=midindex-1;
}
}
}
int main()
{
int array_size=-1;
int a[100];
ifstream fin;
get_input (fin, a, 100, array_size);
binary_search (a, array_size);
return 0;
}
void get_input (ifstream& fin, int a[], int size, int & array_size)
{
fin.open("numbers.txt");
if (fin.fail())
{
cout << "File failed to open";
exit(1);
}
for(int i = 0; i < size; i++)
{
a[i] = 0;
}
cout << "The numbers in the array are: \n\n";
for (int i = 0; i < size; i++)
{
if (!fin.eof())
{
fin >> a[i];
array_size ++;
}
}
for (int i = 0; i < array_size; i++)
{
cout << a[i] << " ";
}
cout << "\n\n\n";
cout << "The numbers in the array sorted are: \n\n";
for(int i = 0; i < array_size; ++i)
{
int temp2 = a[i];
for (int j = i+1; j < array_size; ++j)
{
if(a[j] < temp2)
{
temp2 = a[j];
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
for (int i = 0; i < array_size; i++)
{
cout << a[i] << " ";
}
cout << "\n\n\n";
fin.close();
}
當完成程序時,假設從文件中獲取輸入將其分配給數組,然後對數組進行排序。在此之後,我需要使用二進制搜索來查找用戶給出的數字,並將其在數組中的位置顯示給用戶。
更新:找到索引發現錯誤的輸出....我應該只添加一個midindex?
void binary_search (int a[], int & array_size)
{
cout << "Please enter the element you would like to search for \n";
int element;
cin >> element;
int lastindex=array_size-1, startindex=0;
while (startindex <= lastindex)
{
int midindex= startindex + (lastindex - startindex)/2;
if(element > a[midindex])
{
startindex=midindex+1;
}
else if (element < a[midindex])
{
lastindex=midindex-1;
}
else if (element == a[midindex])
{
cout<<"Element "<<element<<" found at index "<<midindex<<endl;
return;
}
}
}
凡去用它的指數?首先,你應該將I/O從搜索功能中分離出來,並將元素作爲參數傳遞給函數。 – 2010-10-21 03:25:16
爲什麼不使用'std :: vector','std :: swap'等? – GManNickG 2010-10-21 03:29:14
@GMan不得不手動編碼。或者我會。 – Zud 2010-10-21 03:31:50