作为我研究的一部分,我们正在学习使用“堆”,并负责编写一个简短的数学程序,使用指针来引用和尊重堆。作为一些个人学习,我尝试通过创建一个数组并在其上使用二进制搜索来复制它。但它根本行不通。
这是我的代码:
#include <iostream>
#include <Windows.h>
using namespace std;
int main()
{
//creating pointers
int* ii = new int;
int* top = new int;
int* bottom = new int;
int* uArray = new int[12];
int* uChoice = new int;
//assigning values in location of pointer
*ii = 5;
*top = 11;
*bottom = 0;
cout<<"Please input a value between 1 and 12 to find in the array: \t";
cin >> *uChoice;
for (int x = 0; x<12; x++) //adding values into the array
{
uArray[x] = x;
cout<<x;
Sleep(1000);//checking loop works
}
while (uArray[*ii] != *uChoice)
{
if (uArray[*ii] > *uChoice)
{
*bottom = *ii;
*ii = (*top + *bottom)/2;
}
else
{
*top = *ii;
*ii = (*top + *bottom) /2;
}
if (*uChoice == *ii)
{
break;
}
}
//clearing pointers.
delete ii;
delete top;
delete bottom;
delete uArray;
ii = 0;
top = 0;
bottom = 0;
uArray = 0;
cout<<uChoice<<" Found at position: \t"<< *ii;
Sleep(10000);
return 0;
}
提前谢谢了。
[编辑:] 错误发生在 while 循环中。发生了一些事情,这意味着它没有正确搜索数组。对不起,我没有澄清这一点。