【发布时间】:2020-03-15 16:12:07
【问题描述】:
我已经尝试过单独使用向量而不是固定内存数组进行搜索,并且效果非常好。但是现在当我尝试首先对向量进行排序 以使其能够在二分搜索中工作 时,程序在用户输入向量列表后停止 这是代码
#include <iostream>
#include <vector>
using namespace std;
void BubbleSort(vector<int>list){
int temp;
for (int i=0;i<list.size();i++){
for (int j=1;j<list.size();j++){
if(list[i]>list[j]){
list[i]=temp;
list[j]=list[i];
temp=list[j];
}
}
}
}
int Binary_search(vector<int>list,int target){
int maximum=(list.size())-1;
int minimum = 0;
int mean;
while (maximum>minimum){
mean = (maximum+minimum)/2;
if (list[mean] == target){
cout << "The number you're looking for is found! \n";
return mean;
}
else if(list[mean] > target){
maximum = mean;
}
else{
minimum = mean;
}
}
return -1;
}
int main()
{
unsigned int k;
int x,a,target;
vector<int>list;
cout << "Enter the amount of numbers you want to enlist \n";
cin >> k;
while((list.size()< k) && (cin >> x)){
list.push_back(a);
}
BubbleSort(list);
cout << "Enter the target that you want to search for \n";
cin >> target;
int result = Binary_search(list,target);
if(result == -1){
cout << "Your result is not found ";
}
else{
cout << "Your result is found at the index: " << result;
}
return 0;
}
我希望程序进行排序(但不是打印出向量 sorted ,只是从后面排序,然后在搜索后显示结果) 问题肯定出在排序部分,但我不知道在它之前使用冒泡排序是否可以,谁能指出我正确的排序方式然后搜索?
【问题讨论】:
-
for (int j=1;i<list.size();j++)... 仔细查看条件和您在那里使用的变量... -
这很尴尬,我的错,但即使它仍然无法正常工作,它也会继续运行,但程序本身没有完成
-
BubbleSort按值获取其参数,因此排序列表永远不会返回给调用者。它应该通过引用传递:void BubbleSort(vector<int> &list). -
好吧,我没有注意按值/引用传递,虽然每次结果等于-1时它仍然一直显示未找到,是不是以这种方式搜索的问题?
-
仔细查看用于在排序中交换值的三行。它们不正确,但可以正常工作,但重新排列正确。