java-折半查找法

方法一:

package suanfa;

import java.util.*;

public class zheban {

public static void main(String[]args)

{

int[]a={1,3,6,8,9,89,765};

int time=search(a,8);

System.out.println(time);

}

public static int search(int[]a,int key)

{

int low=1;

int high=a.length;

int mid;

while(low<high)

{

mid=(low+high)/2;

if(key==a[mid-1])

return mid-1;

else if(key>a[mid-1])

low=mid+1;

else

high=mid-1;

}

return 0;

}

}



方法二:

package m;

import java.util.*;

public class zheban {

public static int[]data={1,3,5,7,9,11,22,44,67,89};

public static void main(String[]args)

{

System.out.println("please enter the data you will find:");

Scanner scan=new Scanner(System.in);

int key=scan.nextInt();

zheban(key,0,9);

}

public static boolean zheban(int key,int low,int high)

{

int l=low;

int h=high;

int mid;

while(l<h)

{

mid=(l+h)/2;

if(data[mid]==key)

{

System.out.println("find "+"the data is in array "+(mid+1));

return true;

}

else if(key<data[mid])

h=mid-1;

else if(key>data[mid])

l=mid+1;

}

System.out.println("failed");

return false;

}

}


本文出自 “hagar” 博客,谢绝转载!

java-折半查找法,布布扣,bubuko.com

java-折半查找法

上一篇:用python , java 实现全排列


下一篇:java-线性查找法