查找算法(一)二分查找法

package com.algorithm.sort;
 
 public class BinarySearch {
 
 	/**
 	 * 二分查找法
 	 * @param args
 	 */
 	public static void main(String[] args) {
 		int[] sourceArray = {9, 12, 15, 22, 24, 27, 31, 42, 48, 73};
 		int key = 31;
 		String result = search(sourceArray, key, 0, sourceArray.length-1);
 		System.out.println(result);
 	}
 	
 	private static String search(int[] sourceArray, int key, int low, int high){
 		while(high >= low){
 			int middle = low + (high - low)/2;
 			if(sourceArray[middle] == key){
 				return key + "在sourceArray中的第" + middle + "位!";
 			}else if(sourceArray[middle] > key){
 				high = middle - 1;
 			}else{
 				low = middle + 1;
 			}
 			System.out.println(sourceArray[middle]);
 		}
 		return "没有找到该数";
 	}
 }

猜你喜欢

转载自renegade24.iteye.com/blog/1669393
今日推荐