zoukankan      html  css  js  c++  java
  • 在归并排序中对小数组采用插入排序实现代码

     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 }
  • 相关阅读:
    BUUCTF--Youngter-drive
    BUUCTF--CrackRTF
    FireShell CTF 2020 Re Simple Encryption
    2020 美国大学生数学建模论文翻译(week 2)
    仿射密码
    乘法逆元
    RC4加密与解密
    2020 BJDCTF Re encode
    2020美国大学生数学建模(MCM/ICM)A题数据及参考资料
    路由器, 美团笔试题, 差分
  • 原文地址:https://www.cnblogs.com/A-Little-Nut/p/8295068.html
Copyright © 2011-2022 走看看