I'm performing a binary search in an array, looking for a specific value inside of it. When I wrote the code the first time, my for loop for sorting the array in ascending order always added a 0 right in the middle of it so that I could not search for the last element of the array, since the middle part got now replaced with 0 and I don't know why, then I rewrote the program in the exact same way and suddenly it worked.
I noticed in the new rewritten program that when I write a for loop for iterating through the array and printing out its contents before the for loop for sorting the array that it adds a 0 in the middle again, if I delete that for loop everything works fine. I don't understand why that is, could somebody explain that to me please?
#include <iostream>
using namespace std;
int main()
{
int Arr[] = {1,-1,2,-2, 3,-3,4,-4,5,-5,6,-6,7,-7};
int Temp, Size, Low = 0, High, Mid, Key, Found = 0;
Size = (sizeof(Arr) / sizeof(Arr[0]));
High = Size - 1;
cout<<"Enter value of key you want to testsearch for:\n";
cin>>Key;
/*
for (int i = 0; i < Size; i++) //if I don't comment out this loop the 0 will get added in
{ //the middle of the array again and I don't know why
cout<<Arr[i]<<" ";
}
*/
for (int Rep = 1; Rep <= Size-1; Rep++)
{
for (int i = 0, Temp = 0; i < Size; i++)
{
if (Arr[i] > Arr[i+1])
{
Temp = Arr[i];
Arr[i] = Arr[i+1];
Arr[i+1] = Temp;
}
}
}
for (int i = 0; i < Size; i++)
{
cout<<Arr[i]<<" ";
}
for (int i = 0; i < Size; i++)
{
Mid = (Low+High)/2;
if (Arr[Mid] == Key)
{
Found = 1;
break;
}
else if (Arr[Mid] < Key)
{
Low = Mid+1;
}
else if (Arr[Mid] > Key)
{
High = Mid-1;
}
}
if (Found)
{
cout<<"\nGiven key value "<<Key<<" was found.";
}
else
{
cout<<"\nGiven key value "<<Key<<" was not found.";
}
return 0;
}