Using binary, find the element of Key 10 in the following array.
10,14,19,26,27,31,33,35,42,44
#include<iostream>
#include<stdio.h>
#include<bits/stdc++.h>
using namespace std;
int main()
{
int arr[10] = {10,14,19,26,27,31,33,35,42,44};
int start = 0;
int end = 9;
int mid;
bool ans = false;
while(start <=end)
{
mid = start + (end-start)/2;
if(arr[mid] == 10)
{
ans = true;
printf("Element found at index %d", mid);
break;
}
else if(arr[mid]>10)
{
end = mid-1;
}
else{
start = mid+1;
}
}
if(ans == false)
{
printf("Element not found");
}
return 0;
}
Comments
Leave a comment