#include <bits/stdc++.h>
using namespace std;
int linear_search(vector<int> arr, int key)
{
for (int i = 0; i < arr.size(); i++)
if (arr[i] == key)
return i;
return -1;
}
int binary_search(vector<int> arr, int key)
{
int l = 0;
int r = arr.size() - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (arr[mid] == key)
return mid;
else if (arr[mid] < key)
l = mid + 1;
else
r = mid - 1;
}
return -1;
}
int main()
{
vector<int> arr(10000000);
//sorted input 1 to 10000000
for (int i = 0; i < 10000000; i++)
arr[i] = i + 1;
//we will search 5 keys
//key1=3000000
//key2=5000000
//key3=7000000
//key4=9000000
//key5=11000000
vector<int> keys{ 3000000, 5000000, 7000000, 9000000, 11000000 };
// Linear Search time
for (int i = 0; i < 5; i++) {
int res = linear_search(arr, keys[i]);
if (res != -1)
cout << "Key found at : " << res << endl;
else
cout << "Key not found\n";
}
// Binary Search time
for (int i = 0; i < 5; i++) {
int res = binary_search(arr, keys[i]);
if (res != -1)
cout << "Key found at : " << res << endl;
else
cout << "Key not found\n";
}
return 0;
}
Output
Key found at : 2999999
Key found at : 4999999
Key found at : 6999999
Key found at : 8999999
Key not found
Key found at : 2999999
Key found at : 4999999
Key found at : 6999999
Key found at : 8999999
Key not found
0 Comments