#include <iostream>
#include <stdlib.h>
#define LEN 20
int a[LEN];
void merge(int ,int ,int );
void mergesort(int low,int high)
{/*利用分治思想對數組進行劃分*/
int mid;
if(low<high) ///直到將每個數組分爲長度爲1
{
mid=(low+high)/2;
mergesort(low,mid);
mergesort(mid+1,high);
merge(low,mid,high); ///對兩個劃分數組的的合併
}
}
void merge(int low,int mid,int high)
{/*兩數組的歸併操作*/
int b[LEN];
int i,l,h;
i=low;
l=low;
h=mid+1;
while(l<=mid && h<=high)
{
if(a[l]<=a[h]) { b[i]=a[l]; l++;}
else {b[i]=a[h]; h++;}
i++;
}
while(l<=mid) b[i++]=a[l++];
while(h<=high) b[i++]=a[h++];
for(i=low;i<=high;i++)
a[i]=b[i];
}
void print(int *a,int n)
{
int i;
for(i=0;i<n;i++)
cout<<a[i]<<" ";
}
int main(int argc, char *argv[])
{
int n,i,s;
cout<<"請輸入數組元素個數:"<<endl;
cin>>n;
cout<<"請輸入元素:"<<endl;
for(i=0;i<n;i++)
cin>>a[i];
print(a,n);
cout<<endl;
mergesort(0,n-1);
print(a,n);
system("PAUSE");
return 0;
}
分治法:分而治之,在這個程序裏,它把一個數組作爲一個整體慢慢劃分,直到每個元素作爲一個
長度爲1 的數組再進行合併。當數組共有元素N個,2^K=N,則該程序中的遞歸會進行K次,時間復
度爲O(nlogn),但由於在合併時採用一個輔助數組因而佔用空間大,故該算法並不令人十分滿
意。最近上課上的很緊,每次課下來感覺是接觸到不少,只是不知道爲什麼,當時上課總感覺那些
經典算法都懂了,但當真正把它們變成自己的程序時總會出現這樣或那樣的問題,還是覺得把書本
拿出來的好,可能寫的太少,懂得也太少。慢慢從編程現好好體會那些算法的用法及怎麼實現的。
想到沒搞定的就還有好多問題,就那矩陣相乘的動態規劃還存在問題,只待慢慢解決了……