有人可以帮我解决这个问题吗?主要填充从1到1000的1000个随机数的数组,当它进入函数时,它按升序排序,它遵循二进制搜索,但问题是它不打印任何东西。
int f10(int array[], int size)
{
int temp; // temporary swap variable
cout << "Ascending Order:" << endl;
for (int x = 1; x <= size; x++)
{ //how times
for (int j = 1; j <= size; j++)
{
if (array[j] > array[j + 1])
{
//we need to swap
temp = array[j]; //temp is holding the first value
array[j] = array[j + 1]; //
array[j + 1] = temp; //temp holds the second value
}
}
}
for (int x = 1; x <= size; x++)
{
cout << array[x] << ", ";
}
int value;
cout << "\nGimme a number to search:\n\t";
cin >> value;
int left = array[1], right = array[1000];
while (left < right)
{
int middle = (left + right) / 2;
if (array[middle] == value)
{
return middle;
}
else if (array[middle] > value)
{
right = middle - 1;
}
else
{
left = middle + 1;
}
}
return -1;
}
答案 0 :(得分:1)
您的代码中存在很少的错误。检查一下。仅为10个号码执行此操作。通过编写随机数逻辑,使其为1000或任何您喜欢的。
#include <iostream>
int f10(int arr[],int size);
using namespace std;
int main()
{
int arr[10] = {22,53,14,11,75,6,7,1,8,88};
int result_index;
result_index = f10(arr,10);
cout << "Result = "<<result_index<<endl;
}
int f10(int array[], int size) {
int temp; // temporary swap variable
cout << "Default Array:" << endl;
for (int x=0; x < size; x++)
{
cout<< array[x]<<", ";
}
cout << "Ascending Order:" << endl;
for (int x = 0; x < size; x++){
for(int j = 0; j < size; j++) {
if(j != size-1 && array[j] > array[j+1]) { // Major Change
// Swapping
temp = array[j]; //temp is holding the first value
array[j] = array[j+1]; //
array[j+1] = temp; //temp holds the second value
}
}
}
for (int x=0; x < size; x++)
{
cout<< array[x]<<", ";
}
int value;
cout <<"\nGimme a number to search:\n\t";
cin >> value;
int left = 0, right = 9; // Major change
while (left <= right){ // Major change
int middle = (left + right) / 2;
if (array[middle] == value)
{
return middle;
}
else if (array[middle] > value)
{
right = middle - 1;
}
else
{
left = middle + 1;
}
}
return -1;
}