二分法查找数组中的元素并返回其对应的索引

package org.westos.homework;
/**
 * 现要求采用二分法找出指定的数值并将其在数组的索引返回,如果没有找到则返回 -1
 */
import java.util.Arrays;

public class HomeWork02 {
	
	public static int search(int[] arr,int key) {
		Arrays.sort(arr);
		//System.out.println(Arrays.toString(arr));
		int start = 0;
		int end = arr.length-1;
		while(start <= end) {
		int	middle = (start + end)/2;
		if(key < arr[middle]) {
			end = middle-1;
		}else if(key > arr[middle]) {
			start = middle+1;
		}else{
			return middle;
		}
		}
		return -1;
	}

	public static void main(String[] args) {
		int [] arr = {80,40,50,45,90,120,30,20,100};
		System.out.println(search(arr, 40));
		System.out.println(search(arr, 30));
		System.out.println(search(arr, 100));
	}
}
 

运行结果:


你可能感兴趣的:(数据结构与算法,Java--代码练习)