as part of my study we are learning about using the "Heap" and were tasked with writing a short maths program with the use of pointers to reference and deference the heap. As a bit of personal learning I've tried to replicate this with an Array, by creating one and using a Binary Search on it. But it simply won't work.
Here's my code:
#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;
}
Many thanks in advance.
[Edit:] The error occurs within the while loop. Something is happening that means its not correctly searching the array. Sorry i didn't clarify this.
ii,top,bottomanduChoicebe pointers is pointless, don’t do it. Also, be aware that in real code you wouldn’t use pointers at all in this situation, you’d use a container class.