Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- void swap(int &a, int &b) {
- a = a + b;
- b = a - b;
- a = a - b;
- }
- int main() {
- int n;
- cout << "Size of the Array: ";
- cin >> n;
- int arr[n];
- int SearchItem;
- bool found = false;
- cout << "Enter " << n << " Elements: ";
- for(int i = 0; i < n; i++)
- cin >> arr[i];
- // Linear Search
- cout << "Enter the value to find (Linear Search): ";
- cin >> SearchItem;
- for(int i = 0; i < n; i++)
- if(arr[i] == SearchItem) {
- cout << SearchItem << " Found in Location: " << i << endl << endl;
- found = true;
- break;
- }
- if(found == false)
- cout << SearchItem << " Not Found" << endl << endl;
- //Binary Search
- for(int i = 0; i < n - 1; i++) //FOR SORTING (SELECTION)
- for(int j = i + 1; j < n; j++)
- if(arr[i] > arr[j])
- swap(arr[i], arr[j]);
- cout << "Enter the value to find (Binary Search): ";
- cin >> SearchItem;
- int i = 0, j = n, m;
- found = false;
- while(true) {
- m = (i + j) / 2;
- if(arr[m] == SearchItem){
- cout << SearchItem << " Found" << endl;
- found = true;
- break;
- }
- else if(i == m)
- break;
- else if(arr[m] < SearchItem)
- i = m + 1;
- else
- j = m;
- }
- if(found == false)
- cout << SearchItem << " Not Found" << endl << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement