码迷,mamicode.com
首页 > 编程语言 > 详细

自写归并排序 【模板备份】

时间:2018-04-06 18:37:26      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:pre   body   归并排序   str   span   归并   amp   class   out   

 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 }

 

自写归并排序 【模板备份】

标签:pre   body   归并排序   str   span   归并   amp   class   out   

原文地址:https://www.cnblogs.com/xfww/p/8728210.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!