1. 程式人生 > >003—二分查找的實現

003—二分查找的實現

urn 數組 style 改變 system.in scanner ret java next

package oo3_binary_search;

import java.util.Arrays;
import java.util.Scanner;

/**
 * @author ALazy_cat 
 *     二分查找:要求待查表有序。二分查找的基本思想是將n個元素分成大致相等的兩部分,取 a[n/2]與x做比較,
 * 如果x=a[n/2],則找到x,算法中止;如果x<a[n/2],則只要在數組a的左半部分繼續搜索x,如果x>a[n/2],則
 * 只要在數組a的右半部搜索x.
 */
public class BinarySearch {
    public static
void main(String[] args) { int[] a = { 0, 10, 19, 24, 73, 94, 95 }; int pos = 0; System.out.println("數組: " + Arrays.toString(a)); Scanner in = new Scanner(System.in); System.out.print("請輸入關鍵字: "); int key = in.nextInt(); in.close(); System.out.println(
"在數組中搜索數字 " + key + "..."); if ((pos = binarySearch1(a, key)) != -1) { System.out.println(key + " 在數組中的位置是: " + pos); } else { System.out.println(key + "不存在."); } System.out.println("---------------------"); System.out.println("在數組中搜索數字 " + key + "...");
if ((pos = binarySearch2(a, key)) != -1) { System.out.println(key + " 在數組中的位置是: " + pos); } else { System.out.println(key + "不存在."); } } // 二分查找的遞歸實現 // 如果在有序表中有滿足a[i] == key的元素存在,則返回該元素的索引i;否則返回-1 public static int binarySearch1(int[] a, int key) { return binarySearch1(a, key, 0, a.length - 1); } public static int binarySearch1(int[] a, int key, int low, int high) { if (low > high) return -1; int mid = (low + high) / 2; if (a[mid] == key) { return mid; } else if (a[mid] < key) { return binarySearch1(a, key, mid + 1, high); } else { return binarySearch1(a, key, low, mid - 1); } } // 二分查找的循環實現 // 循環條件:low<=high; // 循環體:改變low與high的值即可 public static int binarySearch2(int[] a, int key) { int low = 0; int high = a.length - 1; int mid = 0; while (low <= high) { mid = (low + high) / 2; if (a[mid] == key) { return mid; } else if (a[mid] < key) { low = mid + 1; } else { high = mid - 1; } } return -1; } }

003—二分查找的實現