C++實(shí)現(xiàn)合并排序的方法
更新時(shí)間:2015年07月31日 11:13:31 作者:Jack_Wong2010
這篇文章主要介紹了C++實(shí)現(xiàn)合并排序的方法,實(shí)例分析了合并排序的原理與相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下
本文實(shí)例講述了C++實(shí)現(xiàn)合并排序的方法。分享給大家供大家參考。具體如下:
//合并排序
#include<iostream>
#include<cmath>
using namespace std;
int num[100];
void print(int num[],int len)
{
for(int i=0;i<len;i++)
{
cout<<num[i]<<" ";
}
cout<<endl;
}
void merge(int num[],int beg,int mid,int end)
{
int temp[100];
int t=beg;
int i=beg,j=mid+1;
while(i<=mid&&j<=end)
{
if(num[i]<num[j])
temp[t++]=num[i++];
else
temp[t++]=num[j++];
}
while(i<=mid)
temp[t++]=num[i++];
while(j<=end)
temp[t++]=num[j++];
for(int i=beg;i<=end;i++)
num[i]=temp[i];
}
void mergeSort(int num[],int beg,int end)
{
if(beg==end)
return;
int mid=(beg+end)/2;
mergeSort(num,beg,mid);
mergeSort(num,mid+1,end);
merge(num,beg,mid,end);
}
int main()
{
int len;
while(cin>>len)
{
for(int i=0;i<len;i++)
cin>>num[i];
mergeSort(num,0,len-1);
print(num,len);
}
return 0;
}
希望本文所述對大家的C++程序設(shè)計(jì)有所幫助。
相關(guān)文章
C語言匯編分析傳遞結(jié)構(gòu)體指針比傳遞結(jié)構(gòu)體變量高效的深層原因
本文章使用的工具是vs2010,本篇文章主要講解結(jié)構(gòu)體指針作為參數(shù)傳遞與結(jié)構(gòu)體變量作為參數(shù)傳遞的對比,不談值傳遞與址傳遞的概念2022-10-10
VS?Code安裝及C、C++環(huán)境配置詳細(xì)教程(Windows系統(tǒng))
這篇文章主要介紹了VS?Code安裝及C、C++環(huán)境配置詳細(xì)教程(Windows系統(tǒng)),本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-02-02
c++ std::invalid_argument應(yīng)用
想研究std::invalid_argument的朋友可以參考下2013-01-01

