Created
May 4, 2012 00:32
-
-
Save kdmkdmkdm/2590692 to your computer and use it in GitHub Desktop.
binary
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
| // giBinary.cpp : Defines the entry point for the console application. | |
| // | |
| #include "stdafx.h" | |
| #include <iostream> | |
| using namespace std; | |
| int BinSearch(int data[], int numElements, int searchKey); | |
| int main() | |
| { | |
| bool exit = false; | |
| while (!exit) | |
| { | |
| int searchKey = 0; | |
| int data[] = {1, 4, 5, 6, 9, 14, 21, 23, 28, 31, 35, 42, 46, 50, 53, 57, 62, 63, 65, 74, 79, 89, 95}; | |
| cout << "{1, 4, 5, 6, 9, 14, 21, 23, 28, 31, 35, 42, 46, 50, 53, 57, 62, 63, 65, 74, 79, 89, 95}" << endl; | |
| cout << "Enter search key (or 'x' to exit): "; | |
| cin >> searchKey; | |
| cout << searchKey << "is in position " << BinSearch(data[], 23, searchKey) << "." << endl; | |
| } | |
| } | |
| int BinSearch(int data[], int numElements, int searchKey) | |
| { | |
| int a = 0; | |
| int b = numElements - 1; | |
| int m = (a + b) / 2; | |
| while (m != searchKey) | |
| { | |
| m = (a + b) / 2; | |
| if(searchKey < data[m]) | |
| { | |
| b = m; | |
| } | |
| else if (searchKey > data[m]) | |
| { | |
| a = m; | |
| } | |
| else if (searchKey == data[m]) | |
| { | |
| return m; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment