public static int Magicslow (int[] array)
{
for (int i=0;i<array.length;i++)
{
if (array[i]==i)
{
return i;
}
}
return-1;
}
public static int magicfast (int [] array,int start,int end)
{
if (end<start| | start<0| | End>array.length) {
return-1;
}
int mid= (start+end)/2;
if (array[mid]==mid)
return mid;
Else if (array[mid]>mid)
{
return Magicfast (array , start,mid-1);
}else
{
return Magicfast (array,mid+1,end);
}
}
public static int magicfast (int[] array)
{
return Magicfast (array,0,array.length-1);
}
/span>
public static int Magicfast (int[] array,int start,int end)
{
if (End<start | | start<0| | End>=array.length)
{
return-1;
}
int midindex= (start+end)/2;
int Midvalue=array[midindex];
if (Midvalue==midindex)
{
return midindex;
}
/*
Search the left half of the section
*/
int leftindex=math.min (midindex-1,midvalue);
int Left=magicfast (ARRAY,START,LEFTINDEX);
if (left>=0)
return left;
/*
Search the right half of the section
*/
int Rightindex=math.max (midindex+1,midvalue);
int Right=magicfast (array,rightindex,end);
return right;
public static int magicfast (int[] array)
{
Return Magicfast (array,0,array.length-1);
}
}
Note: If the array elements are different, the execution of this method is almost identical to the first solution.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Find a Magic index in array a