// 10.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
#include<algorithm>
#include<ctime>
#define N 10
#define MAX_NUM 10000
using namespace std;
/*打印输出数组内容*/
void print(int *array, int length){
for(int i=0;i<length-1;i++)
cout<<array[i]<<" ";
cout<<array[length-1]<<endl;
}
/*插入排序*/
void InsertSort(int *array){
for(int i=1;i<N;i++){
int temp=array[i];
int j=i-1;
while(j>=0&&array[j]>temp){
array[j+1]=array[j];
--j;
}
array[j+1]=temp;
}
}
/*数据归并*/
void Merge(int *array, int low, int mid, int high){
int length_left=mid-low+1;
int length_right=high-mid;
int *left=new int[length_left+1];
int *right=new int[length_right+1];
int i=0,j=0,k=0;
for(i=0;i<length_left;i++)
left[i]=array[low+i];
left[length_left]=MAX_NUM;
for(i=0;i<length_right;i++)
right[i]=array[mid+i+1];
right[length_right]=MAX_NUM;
for(i=0,j=0,k=low;k<=high;k++){
if(left[i]<=right[j])
array[k]=left[i++];
else
array[k]=right[j++];
}
delete[] left;
delete[] right;
}
/*归并排序*/
void MergeSort(int *array, int low, int high){
if(low<high){
int mid=(low+high)/2;
MergeSort(array, low, mid);
MergeSort(array, mid+1, high);
Merge(array,low, mid, high);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
srand((unsigned int)time(NULL));
int *array=new int[N];
for(int i=0;i<N;i++)
array[i]=rand()%100;
print(array,N);
//InsertSort(array);
MergeSort(array, 0, N-1);
print(array,N);
delete []array;
return 0;
}
插入排序与归并排序
最新推荐文章于 2024-03-28 00:29:10 发布