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

在归并排序中对小数组采用插入排序实现代码

时间:2018-01-16 10:20:38      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:blog   插入排序   body   color   name   --   long   div   []   

 1 #include<iostream>
 2 using namespace std;
 3 void Insertion_sort(long int a[],int s,int n){
 4     int temp,i,j;
 5     for(i=s+1;i<s+n;i++){
 6         temp=a[i];
 7         for(j=i-1;j>=s;j--){
 8             if(a[j]>temp) a[j+1]=a[j];
 9             else break;
10         }
11         a[j+1]=temp;
12     }
13 }
14 void Merge(long int a[],int l,int r,int rend,long int temp[]){
15     int lend=r-1,n=rend-l+1,t=l;
16     while(l<=lend&&r<=rend){
17         if(a[l]<a[r]) temp[t++]=a[l++];
18         else temp[t++]=a[r++];
19     }
20     while(l<=lend) temp[t++]=a[l++];
21     while(r<=rend) temp[t++]=a[r++];
22     for(int i=0;i<n;i++)
23         a[rend]=temp[rend--];
24 }
25 void Msort(long int a[],int l,int rend,long int temp[]){
26     if(rend-l+1>100){
27         if(l<rend){
28             int mid=(l+rend)/2;
29             Msort(a,l,mid,temp);
30             Msort(a,mid+1,rend,temp);
31             Merge(a,l,mid+1,rend,temp); 
32         }
33         else 
34             return;
35     }
36     else 
37             Insertion_sort(a,l,rend-l+1);
38 }
39 void Merge_sort(long int a[],int n){
40     long int *temp=new long int[n];
41     Msort(a,0,n-1,temp);
42     delete []temp;
43 }
44 int main(){
45     int n;
46     cin>>n;
47     long int a[n];
48     for(int i=0;i<n;i++){
49         cin>>a[i];
50     }
51     Merge_sort(a,n);
52     for(int i=0;i<n;i++){
53         i>0?cout<<" "<<a[i]:cout<<a[i];
54     }
55     return 0;
56 }

 

在归并排序中对小数组采用插入排序实现代码

标签:blog   插入排序   body   color   name   --   long   div   []   

原文地址:https://www.cnblogs.com/A-Little-Nut/p/8295068.html

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