Find a Magic index in array a

Source: Internet
Author: User


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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.