数组、排序和二进制搜索

Arrays, sorting and binary searching

本文关键字:二进制 搜索 排序 数组      更新时间:2023-10-16

发现自己对当前的项目有点卡住了。我正在尝试将一个.txt文件(名字和姓氏分别用 1 行空格分隔)读入数组。在文件中读取后,这是应该发生的事情。

  • 使用函数对数组进行排序(我选择了选择排序)
  • 要求用户输入名称
  • 使用函数执行二叉搜索
  • 如果找到,则显示姓名是否为好友

对于其中的大部分,我都理解。该程序早些时候正在读取文件,我什至将其写出来以显示只是为了查看,即使它不是必需的。现在它只显示一个名称。寻找一点帮助让我再次动起来。如果我的屁股很痛,或者我的代码被抬高了,请道歉。感谢您的任何帮助。

#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
//Function prototypes
void nameSort(string[], const int);
//prototype to display the contents of the file after sorting
//Although I do not need this I wanted to see the names were
//read in correctly.
void nameDisplay(string[], const int);
void nameSearch(string[], const int);
int index = 0; //loop counter
int main()
{
const int ARRAY_SIZE = 100;
string nameArray[ARRAY_SIZE];
//file object
ifstream fileIn;
fileIn.open("myFriends.dat");
while (index < ARRAY_SIZE && getline(fileIn, nameArray[index]))
index++;
//function call to sort the array
nameSort(nameArray, index);
//Display names to screen as a test of the sort
nameDisplay(nameArray, ARRAY_SIZE);
//function call for search
nameSearch(nameArray, ARRAY_SIZE);

system("pause");
return 0;
}
//function definitions
void nameSort(string *array, const int ARRAY_SIZE)
{
bool swap;
string temp;
do
{
    swap = false;
    for (int count = 1; count < (ARRAY_SIZE - 1); count++)
    {
        if(array[count-1] >array[count])
        {
            temp = array[count-1];
            array[count-1] = array[count];
            array[count] = temp;
            swap = true;
        }
    }
}
while(swap);
}
void nameSearch(string *array, const int ARRAY_SIZE)
{
int first = 0;
int last = ARRAY_SIZE - 1;
int middle;
string name;
bool friends = false;
do
{
    cout<<"Please enter a name or END to terminate:";
    cin>>name;
}
    while(!friends && first <= last && name != "END");
    {
        middle = (first + last) / 2;
        if (array[middle] == name)
        {
            friends = true;
            cout<<array[middle]<<" is my friend."<<endl;
        }
        else if (array[middle] > name)
            last = middle - 1;
        else 
            last = middle + 1;
    }
} 

void nameDisplay(string *array, const int ARRAY_SIZE)
{
for(int index = 0; index < ARRAY_SIZE; index++)
    cout<<array[index]<<endl;
}

你的名字搜索似乎至少有一个错误。而不是:

while(!friends && first <= last && name != "END");
{
    middle = (first + last) / 2;
    if (array[middle] == name)
    {
        friends = true;
        cout<<array[middle]<<" is my friend."<<endl;
    }
    else if (array[middle] > name)
        last = middle - 1;
    else 
        last = middle + 1;
}

应该有:

while(!friends && first <= last && name != "END");
{
    middle = (first + last) / 2;
    if (array[middle] == name)
    {
        friends = true;
        cout<<array[middle]<<" is my friend."<<endl;
    }
    else if (array[middle] > name)
        last = middle - 1;
    else 
        first = middle + 1;
}