Magic Index

/***9.3
A magic index in an array A[0, 1, ..., n-1] is defined to be an index such that A[i] = i.
Given a sorted array, write a method to find a magic index, if one exists, in array A.
FOLLOW UP:
What if the values are not distinct?
***/

#include<iostream>

using namespace std;

bool isMagic(int *a, int begin, int end) {
       if(begin > end) return false;
       int mid = (begin + end) / 2;
       if(mid == a[mid] ) return true;
       else if(mid < a[begin]) return isMagic(a, mid+1, end);
       else if(mid > a[end]) return isMagic(a, begin, mid-1);
       else {
              if(isMagic(a, begin, mid-1)==true || isMagic(a, mid+1, end) == true)
                     return true;
              else return false;
       }
}

void main() {
       int a[] = {1, 1, 3, 4, 5};
       int sz = sizeof(a) / sizeof(int);

       if(isMagic(a, 0, sz-1) == true)
              cout<<"magic"<<endl;
       else cout<<"nothing"<<endl;

}

Comments

Popular posts from this blog

Sudoku

Longest prefix matching - trie

Climbing Stairs