您的位置:首页 > 编程语言 > Java开发

两种方式Java实现二分查找法

2017-04-29 15:04 218 查看
小树今天使用递归方法实现了二分查找法,也写了普通的二分查找法,代码如下:

import java.util.*;

public class BinarySort {
public static void main(String[]args){
int A[]={2,32,4,12,22,31,20,45,13,23};
BitSort.bitSort(A);//调用位排序算法进行排序
System.out.println("A数组排序后结果:");
for(int i=0;i<A.length;i++)
System.out.print(A[i]+" ");
System.out.println();
System.out.println("递归二分查找法的结果:"+recursiveBinarySearch(A,23));
System.out.println("普通二分查找法的结果:"+binarySearch(A,23));
}

//递归二分查找法
public static int recursiveBinarySearch(int[]list,int key)
{
int low=0;
int high=list.length-1;
return recursiveBinarySearch(list,key,low,high);
}
public static int recursiveBinarySearch(int[]list,int key,int low,int high)
{
if(low>high)//找不到相应的key
return -low-1;
int mid=low+(high-low)/2;//此处必须加上low,否则会发生StackOverFlowError,因为(high-low)的值在发生变化

if(key==list[mid]) return mid;
else if(key<list[mid])
return recursiveBinarySearch(list,key,low,mid-1);
else
return recursiveBinarySearch(list,key,mid+1,high);
}

//普通二分查找法
public static int binarySearch(int []A,int key)
{
int low=0;
int high=A.length-1;

while(low<=high)
{
int mid=low+(high-low)/2;
if(key==A[mid])
return mid;
else if(key<A[mid])
high=mid-1;
else
low=mid+1;
}
return -1;
}
}


运行结果:

bits的内存:64

A数组排序后结果:

2 4 12 13 20 22 23 31 32 45

递归二分查找法的结果:6

普通二分查找法的结果:6
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: