二分查找的非递归实现

二分查找常见的都是递归的实现形式,这里实现了一种非递归的二分查找:
import java.util.Scanner;


public class BinarySearchNonRecursively {
	
	public static int binarySearch( int length, int[] array, int start, int end, int key){
		
		//判断输入是否合法
		if (array == null || start < 0 || end <0 || end < start || key < array[start] || key >array[end]){  
			return -1;
		}
		
		int middle = (start+end)/2;
		
		//判断初始middle位置值是否为要查找的值
		if (array[middle] == key){
			return middle;
		}
		else{
			//开始循环
			while (array[middle] != key){
				//如果新的一轮循环开始时,start处值大于要查找值或end处值小于要查找值,说明要查找的值不在数组中
				if (array[start]>key || array[end]<key){
					return -1;
				}
				else if (array[middle] > key){
					end = middle-1;
				}
				else{
					start = middle+1;
				}
				middle = (start+end)/2;
			}
			return middle;	
		}
	}
	
	public  static void main(String[] args){
		
		Scanner sc1 = new Scanner(System.in);
		System.out.println("Please input the length of the array:");
		int length = sc1.nextInt();

		System.out.println("Please input the array:");
		int[] a = new int[length];
		for (int i=0; i<length; i++){
			a[i] = sc1.nextInt();			
		}		

		System.out.println("Please input the key:");
		int key = sc1.nextInt();
		sc1.close();
		
		System.out.print(binarySearch(length, a, 0, length-1, key));
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值