Created
May 16, 2017 09:12
-
-
Save porimol/77e4dd32a0e1f1218b0977c2afc5f4a2 to your computer and use it in GitHub Desktop.
Binary Search Algorithm Implementation Using C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @file binary_search.cpp | |
* @author Porimol Chandro, CSE 32D, World University of Bangladesh(WUB) | |
* @date 16/05/2017 | |
* | |
* @brief Binary Search Algorithm Implementation. | |
*/ | |
#include <iostream> | |
using namespace std; | |
int main() | |
{ | |
int A[25] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}; | |
int target = 61, mid, lower = 0, upper = (sizeof(A) / sizeof(int))-1; | |
while(lower <= upper){ | |
mid = (lower+upper)/2; | |
if(A[mid] == target){ | |
cout << "The value is found.\nThe index is: " << mid <<", value is: " << A[mid] << endl; | |
break; | |
} else if(A[mid] < target){ | |
lower = mid+1; | |
} else{ | |
upper = mid-1; | |
} | |
} | |
if(lower > upper){ | |
cout << "The value is not found." << endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment