Created
August 24, 2013 20:02
-
-
Save ygabo/6330135 to your computer and use it in GitHub Desktop.
A magic index in an array A[l.. .n-l] is defined to be an index such that A[i] =
i. Given a sorted array of distinct integers, write a method to find a magic index, if
one exists, in array A.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <vector> | |
#include <math.h> | |
#include <map> | |
#include <fstream> | |
#include < ctime > | |
#include <algorithm> | |
#include <vector> | |
#include <iostream> | |
using namespace std; | |
int main(){ | |
int d[] = { -40,-20,-1,1, 2,3,5,6,8,12,13}; | |
vector<int> x(begin(d), end(d)); | |
int left= 0, right = x.size()-1; | |
int mid = (left+right)/2; | |
while( left <= right ){ | |
if( x[mid] < mid ) | |
left = mid+1; | |
else if( x[mid] > mid ) | |
right = mid-1; | |
else { | |
cout << mid << endl; | |
break; | |
} | |
mid = (left+right)/2; | |
} | |
cout << endl << "Done." <<endl; | |
cin.get(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment