1. 程式人生 > >Java學習第15天—折辦查詢

Java學習第15天—折辦查詢

二分查詢

 前提:陣列已經有序

每次都拿中間索引的值和其他索引的值進行比較,如果相等,就返回中間元素的索引

如果比要找的數小,說明要找的數在中間索引的右邊,改變查詢範圍的左邊界,將左邊界變成原陣列的中間位置

如果必要查詢的數大,說明要找的數在中間索引的左邊,改變查詢範圍的右邊界,將右邊界變成陣列的中間位置

package com.nim.day15;
/*
 * 二分查詢
 * 折半查詢
 * 前提條件:查詢的陣列必須是有序的
 * 每次都用中間的元素和要找的元素進行比較
 */
public class BinarySearchDemo {

	public static void main(String[] args) {
		int[] arr = {1,3,5,7,9,10,14};
		int index = binarySearch(arr,6);
		if(index < 0){
			System.out.println("no such element");
		}else{
			System.out.println("index is:" + index);
		}

	}
	//自定義二分查詢方法(需不需要返回值;有沒有引數)
	public static int binarySearch(int[] arr, int value){
		int min = 0;
		int max = arr.length - 1;
		int mid = (min + max)/2;
		//不知道比較的次數,用while迴圈
		while(arr[mid] != value){
			//判斷要找的數落在左邊還是右邊
			if(arr[mid] < value){
				min = mid + 1;
			}else if(arr[mid] > value){
				max = mid - 1;
			}else{
				return mid;
			}
			//重新設定中間的索引值
			mid = (min + max)/2;
			//設定迴圈中指條件
			if(min > max){
				return -1;
			}
		}
		return mid;
	}

}