(經典) K&R的名著<<C程式設計語言>>二分尋找

來源:互聯網
上載者:User

標籤:search   演算法   log   名著   int   遞迴   二分   程式設計   程式   

#include<stdio.h>//尋找成功則返回所在下標否則返回-1int binsearch(int A[], int n,int a){   int low, high, mid;   low = 0;   high = n -1;   while ( low <= high) {    /// 這裡必須是 <=        mid = (low+high) / 2;        if (A[mid] == a)           return mid;        else if(A[mid]<a)           low = mid +1;        else           high=mid-1;    }   return -1;}int main(){   int a[]={1,2,44,44,99};    printf("%d",binsearch(a,5,44));}
//二分尋找,遞迴演算法#include <iostream>#include<stdio.h>using namespace std;int binSearch(int a[],int low,int high,int b){    int mid = (high-low)/2;    if(a[mid] == b) return mid;    if(a[mid] > b)  binSearch(a,low,mid-1,b);    if(a[mid] < b)  binSearch(a,mid+1,high,b);}int main(){   int a[] = {2,6,8,88888,88888888}; int yy;    yy = binSearch(a,0,4,8);    printf("%d",yy);    return 0;}

 

(經典) K&R的名著<<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.