You can find quality tech news,tricks,study materials etc contact me:facebook.com/ashwin.sunilkumar
Support Me...........
Please support me by giving donation
contact: aswinavofficial@gmail.com
Total Pageviews
Monday, September 1, 2014
C++ program to perform Binary Search
// Iterative Binary Search
#include
#include
#include
using namespace std;
/** This is the important part **/
int binarySearch(int haystack[], int needle, int length) {
int low = 0;
int high = length;
int mid = (low+high)/2;
while (high >= low) {
if (haystack[mid] == needle)
return mid;
else {
if (needle > haystack[mid])
low = mid + 1;
else
high = mid - 1;
mid = (low+high)/2;
}
}
return -1; // not found
}
/** *** **/
int main() {
// Replace haystack with user input if needed
// Haystack MUST BE SORTED
int haystack[10] = {10, 11, 20, 22, 30, 33, 40, 44, 50, 55};
int length = sizeof(haystack)/4;
srand(time(NULL));
int needle = haystack[rand()%10];
cout << "This is the array: ";
for (int i=0; i
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment