1. 程式人生 > >自寫歸並排序 【模板備份】

自寫歸並排序 【模板備份】

space str else ret OS AR n) names %d

 1 #include<iostream>
 2 using namespace std;
 3 #include<cstring>
 4 #include<cstdio>
 5 #include<cstdlib>
 6 int cs = 0;
 7 
 8 void merge(int source[], int temp[], int l, int mid, int r) {
 9     int i = l, j = mid + 1;
10     int point = l;
11     while (i < mid + 1
&& j < r + 1) { 12 if (source[i] < source[j]) 13 temp[point++] = source[i++],cs+=1; 14 else 15 temp[point++] = source[j++],cs+=1; 16 } 17 while (i < mid + 1) 18 temp[point++] = source[i++],cs+=1; 19 while (j < r + 1
) 20 temp[point++] = source[j++],cs+=1; 21 for (i = l; i <= r; i++) 22 source[i] = temp[i]; 23 } 24 25 void mergesort(int source[], int temp[], int l, int r) { 26 if (l >= r) return; 27 int mid = (l + r) / 2; 28 mergesort(source, temp, l, mid); 29 mergesort(source, temp, mid + 1
, r); 30 merge(source, temp, l, mid, r); 31 } 32 int a[510000]; 33 int t[510000]; 34 int main(){ 35 int n; 36 scanf("%d",&n); 37 for(int i=0;i<n;i++) 38 scanf("%d",&a[i]); 39 mergesort(a,t,0,n-1); 40 for(int i=0;i<n;i++){ 41 printf("%d",a[i]); 42 if(i!=n-1) 43 putchar( ); 44 } 45 cout<<endl; 46 cout<<cs<<endl; 47 }

自寫歸並排序 【模板備份】