自己对归并排序的理解:
归并排序采用分治法来实现,将要排序的数组对半拆分,当拆分到单个元素的时候,在进行合并这时按照一定的顺序合并到临时数组temp中,最后在存入原来的数组中。
代码:
1 #include2 #include 3 #include 4 #include 5 #include 6 #include 7 #include 8 #define FRE() freopen("in.txt","r",stdin) 9 #define INF 0x3f3f3f3f10 11 using namespace std;12 typedef long long ll;13 const int maxn = 5005;14 int a[maxn],temp[maxn];//负责度O(N*logN)15 16 void mergearrge(int a[],int st,int mid,int en,int temp[])//合并数组17 {18 int i = st,j = mid+1;19 int k = 0;20 while(i <= mid && j <= en)21 {22 if(a[i] <= a[j])23 temp[k++] = a[i++];24 else25 temp[k++] = a[j++];26 }27 while(i <= mid)28 temp[k++] = a[i++];29 while(j <= en)30 temp[k++] = a[j++];31 for(int i = 0; i < k; i++)32 a[st + i] = temp[i];33 }34 35 void mergesort(int a[],int st,int en,int temp[])//拆分数组36 {37 if(st < en)38 {39 int mid = (st + en) / 2;40 mergesort(a, st, mid, temp);41 mergesort(a, mid+1, en, temp);42 mergearrge(a, st, mid, en, temp);43 }44 }45 46 int main()47 {48 a[0] = 5;a[1] = 10;49 a[2] = 45;a[3] = 11;50 a[4] = -1;a[5] = 900;51 mergesort(a, 0, 5, temp);//注意开始和结束下标的填法52 for(int i =0; i < 6; i++)53 printf("%d ",temp[i]);54 return 0;55 }