1. 程式人生 > 其它 >快速排序與二分查詢的應用——判斷號碼是否中獎

快速排序與二分查詢的應用——判斷號碼是否中獎

技術標籤:Java快速排序二分查詢

有一個序列:8,4,20,100,23,34,12,88,66,9。從鍵盤中任意輸入一個數據,判斷序列中是否包含此數,如果包含則提示使用者中獎

先通過快速排序,將中獎號碼按照升序排列

public static void quickSort(int[] arr, int low, int high) {
		// 快速排序
		if (low < high) {
			int index = getIndex(arr, low, high);//找尋基準元素的正確索引
			quickSort(arr, low, index - 1);//對基準元素前的序列進行排序
quickSort(arr, index + 1, high);對基準元素後的序列進行排序 } } public static int getIndex(int[] arr, int low, int high) { // 基準元素 int temp = arr[low]; while (low < high) { // 當隊尾元素大於等於基準元素時,向前挪動high指標 while (low < high && arr[high] >= temp) { high--; } // 如果隊尾元素小於temp,需要將其賦值給low
arr[low] = arr[high]; // 當隊尾元素大於temp時,向前挪動low指標 while (low < high && arr[low] <= temp) { low++; } // 當隊首元素大於temp時,需要將其賦值給high arr[high] = arr[low]; } // 當low和high相等跳出迴圈,此時的low或high就是temp的正確索引位置 // low位置的值並不是temp,所以需要將temp賦值給arr[low] arr[low] = temp; return low;
// 返回基準元素位置 }

再通過二分查詢,判斷輸入的號碼是否中獎

	public static int binarysearch(int arr[], int n, int key) {
		// 折半查詢
		int low = 0, high = n - 1, mid;
		if (arr[low] == key)
			return low;
		if (arr[high] == key)
			return high;
		while (low <= high) {
			mid = (low + high) / 2;
			if (arr[mid] == key)
				return mid;// 查詢成功,返回mid
			if (key > arr[mid])
				low = mid + 1;// 在後半序列中查詢
			else
				high = mid - 1;// 在前半序列中查詢
		}
		return -1;// 查詢失敗,返回-1
	}

最後通過main()方法提示中獎資訊

	public static void main(String[] args) {
		int[] arr = { 8, 4, 20, 100, 23, 34, 12, 88, 66, 9 };
		quickSort(arr, 0, arr.length - 1);
		System.out.print("中獎號碼:");
		for (int i : arr) {
			System.out.print(i + " ");
		}
		System.out.println();
		System.out.println();
		Scanner sc = new Scanner(System.in);
		System.out.print("請輸入要查詢的號碼:");
		int n = sc.nextInt();
		if (binarysearch(arr, arr.length, n) == -1) {
			System.out.println("很遺憾,未中獎!");
		} else
			System.out.println("恭喜你,中獎了!");
	}

以66和67進行測試:
在這裡插入圖片描述
在這裡插入圖片描述