[c++]代码库
// 实验1_1_随机数组合并排序.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
const int N = 10;
int a[N];
void Merge(int left,int mid,int right){
int *temp = new int[right-left+1];
int i=left,j=mid+1,k=0;
while(i<=mid&&j<=right){
if(a[i]<=a[j])
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}
while(i<=mid) temp[k++]=a[i++];
while(j<=right) temp[k++]=a[j++];
for(int i=0,k=left;k<=right;k++,i++)
a[k] = temp[i];
delete[]temp;
}
void Divide(int left,int right){
if(left<right){
int mid=(left+right)/2;
Divide(left,mid);
Divide(mid+1,right);
Merge(left,mid,right);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
srand((unsigned long)time(0));
for(int i=0;i<N;i++)
a[i] = rand()%100;
cout<<"数组:"<<endl;
for(int i=0;i<N;i++)
cout<<a[i]<<" ";
cout<<endl;
Divide(0,N-1);
cout<<"排序:"<<endl;
for(int i=0;i<N;i++)
cout<<a[i]<<" ";
cout<<endl;
return 0;
}
[代码运行效果截图]