1. 程式人生 > >BinarySearch(二分查詢)

BinarySearch(二分查詢)

2016.7.22

對rank()函式進行了修改:

private static int rank(int key, int[] whitelist) {

    int low = 0;
    int high = whitelist.length - 1;
    while(low <= high) {
        int mid = low + (high - low) / 2;
        if(key < whitelist[mid]) {
            high = mid - 1;
        } else if(key > whitelist[mid
]) { low = mid + 1; } else { return mid; } } return -1; }

這樣就不用在main函式裡使用has標籤和for迴圈去判斷key值是否在數組裡面

2016.7.21

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

/**
 * Created by ZYQ on 2016/7/21.
 */
public class BinarySearch {

    // 二分查詢的方法
    private
static int rank(int key, int[] whitelist) { int low = 0; int high = whitelist.length - 1; while(low <= high) { int mid = (low + high) / 2; if(key < whitelist[mid]) { high = mid; } else if(key > whitelist[mid]) { low = mid; } else
{ return mid; } } return -1; } public static void main(String[] args) { int[] whileList=new int[10]; // 輸入陣列中的數 System.out.println("Enter the numbers:"); for(int i = 0; i < 10; i++) { Scanner s = new Scanner(System.in); whileList[i] = s.nextInt(); } // 二分查詢的前提是排好序 Arrays.sort(whileList); System.out.println("Your arrays is:"); // jdk1.5推出的foreach語法 for (int i : whiteList) { System.out.print(i + " "); } System.out.println(); // 輸入要查詢的數 System.out.println("Enter your find numbers:"); Scanner scanner = new Scanner(System.in); while(scanner.hasNextInt()){ int key = scanner.nextInt(); int has = 0; for (int i = 0; i < whileList.length; i++) { if(key == whileList[i]) { has = 1; } } if (has == 1) { int result = rank(key, whileList); System.out.println(key + " is in the position of " + (result + 1)); } else { System.out.println(key+" is not in the array!"); } } } }

今天開始學習資料結構與演算法,寫的第一個演算法,感覺這個我寫的這個程式碼效率不夠高,等學一段時間後再改進!