Aim
·
Linear Search
· Binary Search
Source Code
#include
<iostream>
using
namespace std;
void
takeArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
{
cin >> arr[i];
}
}
int
linearSearch(int arr[], int size, int key)
{
for (int i = 0; i < size; i++)
{
if (arr[i] == key)
{
cout << "key is found at
index ";
return i;
}
}
return -1;
}
int
binarySearch(int arr[], int size, int key)
{
int start = 0;
int end = size - 1;
int mid = (start + end) / 2;
while (start <= end)
{
if (arr[mid] == key)
{
return mid;
}
else if (arr[mid] < key)
{
start = mid + 1;
}
else if (arr[mid] > key)
{
end = mid - 1;
}
mid = (start + end) / 2;
}
return -1;
}
int
main()
{
int arr[100];
int size, key, ch;
cout << "Enter the size of an
Array: ";
cin >> size;
takeArray(arr, size);
while (1)
{
cout << "1.Linear Search
" << endl;
cout << "2.Binary Search
" << endl;
cout << "Enter Your Choice:
";
cin >> ch;
switch (ch)
{
case 1:
cout << "Enter Your Key:
";
cin >> key;
cout << linearSearch(arr,
size, key) << endl
<< endl;
break;
case 2:
cout << "Enter the key
to Search : ";
cin >> key;
int found1 = binarySearch(arr,
size, key);
cout << "key is present
at index " << found1 << endl<< endl;
break;
}
}
}
Result/Output