分治法的基本思想:將一個規模爲n的問題,分解爲k個規模較小的子問題,這些子問題互相獨立且與原問題相同。遞歸的解這些子問題,而後將各個子問題的解合併獲得原問題的解。ios
經典例子:二分搜索算法
算法基本思想:spa
1 將n個元素分紅個數大體相同的兩半,取n/2與x進行比較。code
2 若是找到,則終止,返回。blog
3 若是小於n/2,則在小半部分繼續查找。遞歸
4 若是大於n/2,則在大半部分繼續查找。ci
算法描述代碼:io
#include <iostream> using namespace std; template <class Type> int BinarySearch(Type a[],const Type &x,int n){ int left=0; int right = n-1; while(left<=right){ int middle = (left+right)/2; if(x == middle) return middle; if(x > a[middle]) left = middle+1; else right = middle-1; } return -1; } int main() { int num[10] = {0,9,8,7,6,5,4,3}; int a; cout<<"輸入想要查找的數字:"<<endl; cin>>a; int find = BinarySearch(num,a,9); if(find!=-1) cout<<find<<endl; else cout<<"找不到想要的結果"<<endl; return 0; }
運行結果以下:class