Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "pch.h"
- #include <iostream>
- //Binary search of user entered array
- //Useful code of binary search is at the end of file!
- using namespace std;
- int main()
- {
- const int arrSize = 10;
- //int arr[arrSize] = { 6,1,4,2,8,9,11,3,2,1 };
- //int arr[arrSize] = { 1,1,1,2,2,9,11,1,2,1 };
- //int arr[arrSize] = { 1,2,3,4,5,6,7,8,9,10 };
- //int arr[arrSize] = { 1,2,3,4,5,6,7,9,8,7 };
- //int arr[arrSize] = { 10,9,8,7,6,5,4,3,2,1 };
- int arr[arrSize] = {0};
- //int arr[arrSize] = { 7,3,2,6,5,1,7,3,8,1 };
- cout << "Enter value for " << 1 << " element: ";
- cin >> arr[0];
- cout << endl;
- for (int i = 0; i < arrSize; i++) { cout << arr[i] << " "; }; cout << endl;
- for (int newInsPos = 1; newInsPos < arrSize; newInsPos++)
- {
- cout << "Enter value for " << newInsPos+1 << " element: ";
- cin >> arr[newInsPos];
- cout << endl;
- for (int currInsPos = newInsPos; currInsPos > 0 && arr[currInsPos] < arr[currInsPos - 1]; currInsPos--)
- {
- int tmp = arr[currInsPos - 1];
- arr[currInsPos - 1] = arr[currInsPos];
- arr[currInsPos] = tmp;
- for (int i = 0; i < arrSize; i++) { cout << arr[i] << " "; }; cout << endl;
- }
- }
- for (int i = 0; i < arrSize; i++) { cout << arr[i] << " "; }; cout << endl;
- cout << "Enter search key: ";
- int key;
- cin >> key;
- int left = 0, right = arrSize - 1, mid=0;
- while(1)
- {
- cout << "Finding..";
- mid = (left + right) / 2;
- if (key == arr[mid]) { cout << "Found! Index is:" << mid << endl; break; };
- if (key < arr[mid]) { right = mid - 1; cout << "left side" << endl; }
- if (key > arr[mid]) { left = mid + 1; cout << "right side" << endl; }
- if (left > right) { cout << "Not found!" << endl; break; };
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment