zoukankan      html  css  js  c++  java
  • 递归实现归并排序

     1 /*************************************************************************
     2     > File Name: merge_sort.cpp
     3     > Author:
     4     > Description: 
     5     > Created Time: Sun 26 Jul 2015 10:15:24 AM HKT
     6  ************************************************************************/
     7 
     8 #include<iostream>
     9 using namespace std;
    10 
    11 void merge(int a[],int tmp[],int lPos,int rPos,int rEnd)
    12 {
    13     int numElements=rEnd-lPos+1;// 计算元素个数
    14     int lEnd=rPos-1;
    15     int tmpPos=lPos;
    16     while(lPos<=lEnd && rPos<=rEnd)
    17     {
    18         if(a[lPos]<=a[rPos])
    19             tmp[tmpPos++]=a[lPos++];
    20         else
    21             tmp[tmpPos++]=a[rPos++];
    22     }
    23 
    24     //到这里左端或右端可能还有剩余元素
    25     while(lPos<=lEnd)
    26         tmp[tmpPos++]=a[lPos++];
    27     while(rPos<=rEnd)
    28         tmp[tmpPos++]=a[rPos++];
    29 
    30     for(int i=0;i<numElements;i++)
    31     {
    32         a[rEnd]=tmp[rEnd--];
    33     }
    34 }
    35 
    36 void msort(int a[],int tmp[],int low,int high)
    37 {
    38     if(low>=high)
    39         return;
    40     int middle=(low+high)/2;
    41     msort(a,tmp,low,middle);
    42     msort(a,tmp,middle+1,high);
    43     merge(a,tmp,low,middle+1,high);
    44 }
    45 
    46 void merge_sort(int a[],int len)
    47 {
    48     int *tmp=new int[len];
    49     if(tmp !=NULL)
    50     {
    51         msort(a,tmp,0,len-1);
    52         delete []tmp;
    53     }
    54 }
    55 int main()
    56 {
    57     int a[]={1,4,7,6,3,8,2,5};
    58     merge_sort(a,8);
    59     for(int i=0;i<8;i++)
    60     {
    61         cout<<a[i]<<" ";
    62     }
    63     cout<<endl;
    64 
    65     return 0;
    66 }
    View Code
  • 相关阅读:
    25.Zabbix入门必备
    6.Ansible Roles角色实战
    5.Ansible Jinja2 模板
    4.Ansible Task控制
    3.Ansible varialbes实战
    2.Ansible Playbook剧本
    1.Ansible自动化管理工具
    网站架构面试题必备
    winsows CMD及Linux命令大全 欢迎补充
    Oracle查询表空间
  • 原文地址:https://www.cnblogs.com/wxquare/p/4677317.html
Copyright © 2011-2022 走看看