我已经研究了一段时间了,我已经尝试了多种不同的算法用于我在网上找到的冒泡排序,但它们都没有对我有效,我很接近放弃,但这是明天晚上到期。如果有人能指出我哪里出错了,我真的很感激。我真的不明白这个算法与bool如此恶心尝试找到我之前尝试的东西并在
中编辑它#include <iostream>
using namespace std;
void GetInfo(int[], int&);
void BubbleSort(int[], int);
void BinarySearch(int[], int);
int main()
{
int size;
int array[500];
GetInfo(array, size);
BubbleSort(array, size);
BinarySearch(array, size);
return 0;
}
void GetInfo(int array[], int& size)
{
cout << "Enter the number of naturals: ";
cin >> size;
cout << "Enter the natural numbers to sort: ";
for (int i = 0; i < size; i++)
{
cin >> array[i];
}
}
void BubbleSort(int array[], int size)
{
int temp;
bool check = true;
int end = 0;
while(check)
{
end++;
check = false;
for(int i = 0; i < size - end; i++)
{
if (array[i] > array[i+1]) //I'm positive this part is correct
{
temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
check = true;
}
}
}
cout << endl << "Numbers sorted in ascending order: " << endl;
for (int i = 0; i < size; i++)
{
cout << array[i] << ' ';
}
}
void BinarySearch(int array[], int size) //this doesnt work properly atm but
{ //should be good when the sort works
int index;
int top = size - 1;
int bottom = 0;
int middle = (top) / 2;
bool found = false;
int target;
cout << endl << "Enter the number to search: ";
cin >> target;
while (found == false)
{
if (target > array[middle])
{
bottom = middle + 1 ;
middle = ((top - bottom)/2) + bottom;
}
else if (target < array[middle])
{
top = middle - 1;
middle = ((top - bottom)/2) + bottom;
}
else
{
found = true;
index = middle;
}
}
cout << "Number " << target << " is found in position " << index << endl;
}
答案 0 :(得分:1)
您可能打算在实际交换[size + 1]时将[i]与[i + 1]交换
答案 1 :(得分:1)
这些行错了:
array[i] = array[size+1];
array[size+1] = temp;
你需要:
array[i] = array[i+1];
array[i+1] = temp;