演算法-對分尋找(二分尋找)C++實現,演算法二分

來源:互聯網
上載者:User

演算法-對分尋找(二分尋找)C++實現,演算法二分

這個是個基本的尋找演算法,因為只是把數讀入就需要(N)的時間量,因此我們在說這類問題的時候都是假設讀入過的。

在演算法常用的時間,將問題縮小為一部分(大約1/2),那麼我們就認為這個演算法是O(logn)層級的。


先說下對分尋找的時間複雜度為O(logn)

前提是已經拍序好的數列。


////  main.cpp//  binarySearch////  Created by Alps on 14-7-24.//  Copyright (c) 2014年 chen. All rights reserved.//#include <iostream>int binarySearch(const int A[], int X, int N){    int start = 0, end = 0, mid;    end = N;    while (start <= end) {        mid = (start + end)/2;        if (X > A[mid]) {            start = mid+1;            continue;        }else if (X < A[mid]){            end = mid-1;            continue;        }else{            return mid;        }    }    return -1;}int main(int argc, const char * argv[]){    int A[]={1 ,4 , 6, 8, 19, 34, 93};    int N = sizeof(A)/sizeof(int);    int X = 19;        int locate = binarySearch(A, X, N);    if (locate == -1) {        printf("Can't find the element %d\n",X);    }else{        printf("The element %d is locate in %d\n",X,locate);    }        return 0;}

這裡面沒什麼原理。。問題很簡單~ 


用C語言編寫非遞迴演算法實現折半尋找(二分尋找)

char a[10][5];//按字典序遞增
int search(char *x)//二分尋找,返回有序表中大於等於x的元素位置
{
int low=0,high=9,mid,t;
while(low<=high)
{
mid=(low+high)/2;
t=strcmp(a[mid],x);//比較中點位置與x
if(t==0) return mid;//相等返回其位置
else
if(t>0) high=mid-1;//x小於mid元素,則在中點前
else low=mid+1;
}
return high+1;//返回大於x的第一個元素
}
這個是我曾經用過的字串的二分尋找~
請根據需要修改資料類型。。。
 
二分尋找演算法的C語言實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.