1. 程式人生 > >數組查找

數組查找

dem 定義 dsc 參數 移動 sys == static 折半

1.一般查找:

public class Demo {
	public static void main(String[] asadscgs) {
		int[] arr = { -2, 11, 22, 33, 44, 55, 66, 77, 99, 0, -1 };
		int index = getIndex(arr, -11);
		System.out.println("index=" + index);

	}

	// 定義功能
	public static int getIndex(int[] arr, int key) {
		// 循環遍歷數組,在遍歷的過程中取出數組的中的值和指定的key進行比較
		// 相等就找到,返回當前的下標,如果循環都結束了,也沒有相等的,
		// 說明當前指定的數據,在數組中不存在,
		// 一般只要是程序中關於查找的問題,沒有找到統一都返回-1
		for (int i = 0; i < arr.length; i++) {
			if (arr[i] == key) {
				return i;
			}
		}

		// 如果循環都結束了,說明根本就沒有找到和指定的值相等的數據
		return -1;

	}
}

  

2.折半查找:

public class Demo {
	public static void main(String[] asadscgs) {
		// 定義數組
		int[] arr = { 4, 7, 9, 12, 23, 34, 45, 67 };
		// 調用自定義的折半查找的函數
		int index = binarySearch(arr, 34);
		System.out.println("index=" + index);
	}

	/*
	 * 折半查找的方法 1.有沒有返回值? 有,想要查找數組中某個數據的下標,所以返回要查找數據的下標 如果數組中沒有該數據,則返回-1 2.有沒有參數?
	 * 有,數組和想要查找的數據
	 */
	// 自定義折半查找的函數
	public static int binarySearch(int[] arr, int key) {
		// 定義三個變量並給初始化值
		int start = 0;// 頭角標
		int end = arr.length - 1;// 尾角標
		int min = (start + end) / 2;// 中間角標
		// 使用循環往復控制折半
		while (start <= end) {
			// 對中間的值和指定的值進行比較
			if (key == arr[min]) {
				return min;
			}
			// 指定的值大於中間的值
			if (key > arr[min]) {
				// 頭角標向後移動
				start = min + 1;
			}
			// 指定的值小於中間的值
			if (key < arr[min]) {
				// 尾角標向前移動
				end = min - 1;
			}
			// 如果頭角標和尾角標發生變化,要時刻更新中間角標
			min = (start + end) / 2;
		}
		// 循環結束,說明沒有找到指定的數據
		return -1;
	}
}

  

數組查找