Skip to content

Instantly share code, notes, and snippets.

@ygabo
Created August 24, 2013 20:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ygabo/6330135 to your computer and use it in GitHub Desktop.
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.
#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