二分搜尋演算法的實現

YCH帶帶我發表於2020-11-28
#include <iostream>
#include <time.h>
#include <algorithm>
//二分法的遞迴實現
using namespace std;
int Recursion(int *list, int left, int right, int value)
{
    if(left > right)
        return -1;
    int min_pos = (left + right) / 2;
    if(list[min_pos] == value)
    {
        return min_pos;
    } else if(list[min_pos] > value)
    {
        return Recursion(list, min_pos + 1, right, value);
    } else
    {
        return Recursion(list, left, min_pos - 1,  value);
    }
}
//非遞迴實現二分法
int  Non_Recursion(int *list, int left, int right, int value)
{
    while(left <= right)
    {
        int min_pos = (left + right) / 2;
        if(list[min_pos] > value)
        {
            left = min_pos + 1;
        } else if(list[min_pos] < value)
        {
            right = min_pos - 1;
        } else
            return min_pos;
    }
    return -1;
}
int main()
{
    int *array;
    int length;
    cin >> length;
    array = new int[length];
    for(int i = 0; i < length; i++)
        cin >> array[i];
    sort(array, array + length);
    cout << "請輸入要查詢的元素(-1 為未找到):" << endl;
    int x;
    cin >> x;
    
    clock_t start, finish;
    start = clock();
    cout << "遞迴查詢的位置: " << Recursion(array, 0, length - 1, x);
    finish = clock();
    cout <<endl<<"the time cost is:" << double(finish - start) / CLOCKS_PER_SEC<<endl;
    start = clock();
    cout << "非遞迴查詢的位置: " << Non_Recursion(array, 0, length - 1, x);
    finish = clock();
    cout <<endl<<"the time cost is:" << double(finish - start) / CLOCKS_PER_SEC<<endl;
}

相關文章