标签:有序 归并排序 思想 close 合并 分析 href font gif
对n个不同的数构成的数组A[1..n]进行排序,其中n=2^k.
根据分治的思想,对于每一个待排序的数组,拆分成左右两端,分别对左右两段进行排序,对于已经有序的两个数组把他们合并起来。
1 void merge(int low,int mid,int high)
2 {
3 int i=low,j=mid+1,k=low;
4 while(i<=mid&&j<=high)
5 if(s1[i]<s1[j])
6 s2[k++]=s1[i++];
7 else
8 s2[k++]=s1[j++];
9 while(i<=mid)
10 s2[k++]=s1[i++];
11 while (j<=high)
12 s2[k++]=s1[j++];
13 for ( i = low; i <=high ; i++)
14 {
15 s1[i]=s2[i];
16 cout<<s1[i];
17 }
18 cout<<endl;
19 }
20
21 void mergeSort(int a, int b)
22 {
23 if(a<b)
24 {
25 int mid=(a+b)/2;
26 mergeSort(a,mid);
27 mergeSort(mid+1,b);
28 merge(a,mid,b);
29 }
30 }
数组拆分的复杂度是O( log(n) ),合并数组的复杂度是O(n),总的复杂度是O( nlog(n) )。
https://github.com/Big-Kelly/Algorithm
1 #include <iostream>
2 using namespace std;
3 const int MAX=100;
4 int s1[MAX],s2[MAX];
5 void merge(int low,int mid,int high)
6 {
7 int i=low,j=mid+1,k=low;
8 while(i<=mid&&j<=high)
9 if(s1[i]<s1[j])
10 s2[k++]=s1[i++];
11 else
12 s2[k++]=s1[j++];
13 while(i<=mid)
14 s2[k++]=s1[i++];
15 while (j<=high)
16 s2[k++]=s1[j++];
17 for ( i = low; i <=high ; i++)
18 {
19 s1[i]=s2[i];
20 cout<<s1[i];
21 }
22 cout<<endl;
23 }
24
25 void mergeSort(int a, int b)
26 {
27 if(a<b)
28 {
29 int mid=(a+b)/2;
30 mergeSort(a,mid);
31 mergeSort(mid+1,b);
32 merge(a,mid,b);
33 }
34 }
标签:有序 归并排序 思想 close 合并 分析 href font gif
原文地址:https://www.cnblogs.com/zhang-Kelly/p/12555382.html