#include <iostream>
using namespace std;
int binarySearch(int, int *, int);
int main()
{
int myList[10] = {1,7,13,17,24,38,45,50,100,1000};
int num;
int loc, i;
cout << "The list you entered is: " << endl;
for (i=0; i<sizeof(myList)/sizeof(int); i++)
cout << myList[i] << " ";
cout << endl;
cout << "Enter search item: ";
cin >> num;
cout << endl;
binarySearch(num, myList, sizeof(myList)/sizeof(int));
loc = binarySearch(num, myList, sizeof(myList)/sizeof(int));
if (loc != -1)
cout << "Item found at position " << loc << endl;
else
cout << "Item not in the list" << endl;
system("pause");
return 0;
}
int binarySearch(int item, int *list, int length)
{
int first = 0;
int last = length - 1;
int mid;
bool found = false;
while (first <= last && !found)
{
mid = (first + last) / 2;
if (list[mid] == item)
found = true;
else if(list[mid] > item)
last = mid - 1;
else
first = mid + 1;
}
if (found)
return mid;
else
return -1;
}
int myList[10] = {1,7,13,17,24,38,45,50,100,1000};
int main()
{
int num;
int loc;
cout << "The list you entered is: " << endl;
for(int i=0;i<10;i++) //<---------introduce a loop here to show all the items in the array
cout << myList[i] <<" ";
...
...
}
int binarySearch(int item)
{
// int list; //<----------commented out
int length = 10;
int first = 0;
int last = length - 1;
int mid;
bool found = false;
while (first <= last && !found)
{
mid = (first + last) / 2;
if (myList[mid] == item)<--------added this myList
found = true;
else if(myList[mid] > item)<--------added this myList
last = mid - 1;
else
first = mid + 1;
}
if (found)
return mid;
else
return -1;
}
Join the community of 500,000 technology professionals and ask your questions.
Connect with top rated Experts
14 Experts available now in Live!