1. 程式人生 > 實用技巧 >GitHub Pages Jekyll Liquid 時區timezone問題

GitHub Pages Jekyll Liquid 時區timezone問題

  1. 素數判斷

  2. 遞迴二分查詢

  3. 迴圈二分查詢

一、判斷一個數是否為素數

素數:在大於1的自然數中,除了1和它本身,不再有其他因數的自然數

int checkNumber(int number) {
    if (number < 2) {
        return 0;
    }
    for (int i = 2; i < number; i++) {
        if (number % i == 0) {
            return -1;
        }
    }
    return 1;
}

二、遞迴實現二分查詢

int binarySearch(int
key,int data[],int low,int high) { if (low >= high) { return -1; } int mid = (low + high) / 2; if (key < data[mid]) { return binarySearch(key,data,low,mid); } else if(key >data[mid]){ return binarySearch(key,data,mid+1,high); } else {
return mid; } }

遞迴耗時: 44 ms

三、迴圈實現二分查詢

int binarySearch(int* data,int size,int target) {
    int left = 0;
    int right = size - 1;
    while (left <= right) {
        int mid = (left + right) / 2;
        if (target > data[mid]) {
            left = mid + 1;
        }
        else if(target < data[mid]){
            right 
= mid - 1; } else { return mid; } } return -1; }

耗時:32 ms