Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "iostream"
- #include "cstdlib"
- #include "ctime"
- using namespace std;
- void binarySearch(int a[],int arraySize,int key); //function prototype
- int main()
- {
- const int arraySize = 10;
- int a[arraySize];
- int key,index,to_do = arraySize - 1;
- bool did_swap = true;
- srand(time(NULL));
- for (int i = 0; i <= arraySize; i++)
- {
- a[i] = rand() % 100 + 1; //generating random number between 1 - 100
- }
- while( to_do >= 0 && did_swap)
- {
- index = 0;
- did_swap = false;
- while ( index <= to_do )
- {
- if (a[index] > a[index+1])
- {
- int temp = a[index];
- a[index] = a[index+1];
- a[index+1] = temp;
- did_swap = true;
- }
- index = index+1;
- }
- cout << "to_do=" << to_do <<": ";
- for (int i = 0; i <= arraySize; ++i)
- {
- cout<<a[i]<<" ";
- }
- cout << endl;
- to_do = to_do-1;
- }
- cout <<"Enter search key: ";
- cin >> key;
- binarySearch(a,arraySize,key);
- return 0;
- }
- void binarySearch(int a[],int arraySize,int key)
- {
- bool found = false;
- int low = 0,middle,high = (arraySize - 1),counter = 1;
- while(low <= high)
- {
- cout<<"Pass#"<<counter<<": ";
- for (int i = 0; i < arraySize; ++i)
- {
- if(i == low && low != high)
- {
- cout<<"["<<a[i];
- }
- else if (i == high && low != high)
- {
- cout<<" "<<a[i]<<"]";
- }
- else if (i == low && low == high)
- {
- cout<<"["<<a[i]<<"]";
- }
- else
- {
- cout<<" "<<a[i];
- }
- }
- middle = (low+high)/2;
- if(key == a[middle])
- {
- found = true;
- cout <<endl<<"Found element "<<key<<" at index "<<middle<<endl;
- break;
- }
- else if (key < a[middle])
- {
- high = middle - 1; // search low end of array
- }
- else
- {
- low = middle + 1; // search high end of array
- }
- counter++;
- cout<<endl;
- }
- if(!found)
- {
- cout <<"Could not find element "<<key<<" in array a"<<endl;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement