Created
May 28, 2018 09:33
-
-
Save viniru/a04536775cf75c27e279a052bb19df31 to your computer and use it in GitHub Desktop.
You are given a sorted (from smallest to largest) array A of n distinct integers which can be positive, negative, or zero. You want to decide whether or not there is an index i such that A[i] = i. Design the fastest algorithm that you can for solving this problem
This file contains 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
public class IndexEEle { | |
static int a[] = {-3,-1,0,1,4,6,7,8}; | |
static int flag = 0; | |
public static void find(int l,int h) | |
{ | |
int mid=(l+h)/2; | |
if (mid<a[mid]) | |
find(l,mid-1); | |
else if (mid>a[mid]) | |
find(mid+1,h); | |
else | |
{ | |
flag = 1; | |
System.out.println("The index which is same as the element at its position is "+mid); | |
System.exit(0); | |
} | |
} | |
public static void main(String args[]) | |
{ | |
find(0,a.length-1); | |
if(flag == 0) | |
System.out.println("There is no such element"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment