9. Binary Search
18 May 2020 | STL Programming Practice_1
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int BinarySearch(int M[], int x, int right)
{
int left = 1;
int mid;
while (left<=right)
{
mid = (left+right)/2;
if (M[mid]==x)
return mid+1;
else if (x<M[mid])
right = mid-1;
else
left = mid+1;
}
return -1;
}
int main()
{
int A[] = {2,5,5,6,9,19,26,35,69};
int k = sizeof(A)/sizeof(A[0]);
cout<<BinarySearch(A,9,k);
}
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int BinarySearch(int M[], int x, int right)
{
int left = 1;
int mid;
while (left<=right)
{
mid = (left+right)/2;
if (M[mid]==x)
return mid+1;
else if (x<M[mid])
right = mid-1;
else
left = mid+1;
}
return -1;
}
int main()
{
int A[] = {2,5,5,6,9,19,26,35,69};
int k = sizeof(A)/sizeof(A[0]);
cout<<BinarySearch(A,9,k);
}
Comments