二分搜尋

December 11, 2021

若要搜尋的數列已有排序,應該儘量利用其順序特性,減少搜尋比對次數,這是搜尋的基本原則,二分搜尋是此原則的代表。

解法思路

二分搜尋時數列不斷地分為兩個部份,每次從分割的部份中取中間數比對,如果小於要搜尋的數,由於數列已排序,左邊的數一定都小於要搜尋的對象,不用浪費時間在左邊的數;如果大於搜尋的對象,右邊的數不用再搜尋。

例如在以下的數列搜尋 92,首先中間數索引為 (0 + 9) / 2 = 4(索引由 0 開始):

[3 24 57 57 67 68 83 90 92 95]

由於 67 小於 92,轉而搜尋右邊的數列:

3 24 57 57 67 [68 83 90 92 95]

由於 90 小於 92,再搜尋右邊的數列,這次就找到 92 了:

3 24 57 57 67 68 83 90 [92 95]

如果你將每次切分後選取的數作為節點值,往左切分得到的數作為左子節點,往右切分得到的數作為右子節點,得到的就是二分搜尋樹(Binary Search Tree,BST),假設沒有相同的值,若某節有左子樹,其連接的子節點值,會小於該節點的值,若有右子樹,其後續連接的子節點值,會大於該節點的值。

例如 3 24 57 57 67 68 83 90 92 95 建立起的二分搜尋樹:

二分搜尋

如果從樹根開始,想要搜尋 92,就看看 92 小於或大於節點值,小於就往左子節點,大於就往右子節點,因此從以上的二分搜尋樹來看,比對的節點順序就是 67、90、92。

二分搜尋

程式實作

#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 
#define MAX 10 
#define SWAP(x,y) {int t; t = x; x = y; y = t;} 

void quickSort(int[], int, int); 
int binarySearch(int[], int); 

int main(void) { 
    srand(time(NULL)); 
    
    int number[MAX] = {0}; 

    int i;
    for(i = 0; i < MAX; i++) { 
        number[i] = rand() % 100; 
    } 

    quickSort(number, 0, MAX-1); 

    printf("數列:"); 
    for(i = 0; i < MAX; i++) 
        printf("%d ", number[i]); 

    int find;
    printf("\n輸入尋找對象:"); 
    scanf("%d", &find); 

    if((i = binarySearch(number, find)) >= 0) 
        printf("找到數字於索引 %d ", i); 
    else 
        printf("\n找不到指定數"); 
    
    printf("\n"); 

    return 0; 
} 

int binarySearch(int number[], int find) { 
    int low = 0; 
    int upper = MAX - 1; 
    while(low <= upper) { 
        int mid = (low+upper) / 2; 
        if(number[mid] < find) 
            low = mid+1; 
        else if(number[mid] > find) 
            upper = mid - 1; 
        else 
            return mid; 
    } 
    return -1; 
} 

void quickSort(int number[], int left, int right) { 
    if(left < right) { 
        int s = number[(left+right)/2]; 
        int i = left - 1; 
        int j = right + 1; 

        while(1) { 
            while(number[++i] < s) ;  // 向右找 
            while(number[--j] > s) ;  // 向左找 
            if(i >= j) 
                break; 
            SWAP(number[i], number[j]); 
        } 

        quickSort(number, left, i-1);   // 對左邊進行遞迴 
        quickSort(number, j+1, right);  // 對右邊進行遞迴 
    } 
} 
public class Search {
    public static int binary(int[] number, int des) {
        int low = 0; 
        int upper = number.length - 1; 

        while(low <= upper) { 
            int mid = (low+upper) / 2; 
            if(number[mid] < des) 
                low = mid+1; 
            else if(number[mid] > des) 
                upper = mid - 1; 
            else 
                return mid; 
        } 

        return -1; 
    }
    
    public static void main(String[] args) {
        int[] number = {1, 2, 3, 4, 6, 7, 8};
        int find = Search.binary(number, 2);
        System.out.println(find >= 0 ? "找到數值於索引" + find : "找不到數值"); 
    }
} 
def search(number, des):
    low = 0
    upper = len(number) - 1
    while low <= upper:
        mid = (low + upper) // 2
        if number[mid] < des:
            low = mid + 1
        elif number[mid] > des:
            upper = mid - 1
        else:
            return mid
    return -1

number = [1, 4, 2, 6, 7, 3, 9, 8]
number.sort()
find = search(number, 2)
print("找到數值於索引 " + str(find) if find >= 0 else "找不到數值")  
object Search {
    def binary(number: Array[Int], des: Int) = {
        var low = 0
        var upper = number.length - 1
        var result = -1
        var isContinue = true
        while(isContinue && low <= upper) {
            val mid = (low + upper) / 2
            if(number(mid) < des) {
                low = mid + 1
            }
            else if(number(mid) > des) {
                upper = mid - 1
            }
            else {
                result = mid
                isContinue = false
            }
        }
        result
    }
}

val number = Array(1, 2, 3, 4, 6, 7, 8)
val find = Search.binary(number, 3)
println(if(find >= 0) "找到數值於索引 " + find else "找不到數值")
# encoding: UTF-8
def search(number, des)
    low = 0
    upper = number.length - 1
    while low <= upper
        mid = (low + upper) / 2
        if number[mid] < des
            low = mid + 1
        elsif number[mid] > des
            upper = mid - 1
        else
            return mid
        end
    end
    -1
end

number = [1, 4, 2, 6, 7, 3, 9, 8]
number.sort!
find = search(number, 2)
print find >= 0 ? "找到數值於索引 " + find.to_s : "找不到數值", "\n"
function search(lt, n) {
    let low = 0
    let upper = lt.length - 1;
    while(low <= upper) {
        let mid = Math.floor((low + upper) / 2);
        if(lt[mid] < n) {
            low = mid + 1;
        }
        else if(lt[mid] > n) {
            upper = mid - 1;
        }
        else {
            return mid;
        }
    }
    return -1;
}

lt = [1, 4, 2, 6, 7, 3, 9, 8];
lt.sort((a, b) => a - b);
console.log(search(lt, 2));
binarySearch [] _ = -1
binarySearch lt n = _search lt n 0 (length lt - 1)
    where
    _search lt n low upper =
        if low > upper then -1
        else
            let mid = (low + upper) `div` 2
                elem = lt !! mid
            in
            if elem == n then mid
            else
                if elem < n then _search lt n (mid + 1) upper
                else _search lt n low (mid - 1)
           

main = print $ binarySearch [3, 5, 8, 9, 10, 13, 15] 13

分享到 LinkedIn 分享到 Facebook 分享到 Twitter