# 《算法》实验一归并排序与快速排序 时间的比较

#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include<time.h>
#include "stdlib.h"
using namespace std;
#define size 100000//要很大才有比较结果，不然为0.。是因为计算机太快了吗？   》_《
int A[size] = { 7, 2, 55, 89, 31, 3, 6, 45, 64, 30 }, B[size], C[size];
////////////////////////////////////////////////////////////////////////
//////////////生成N个随机数
void generation()
{
srand((unsigned)time(0)); //要放在外面不然随机数是一样的;因为时间一样，种子？一样，rand出来的数值一样的
for (int i = 0; i < size; i++)
{

A[i] = rand() % 1000000;// 产生随机数
B[i] = A[i];
C[i] = A[i];

}
}
///////////////////////////////////////////////////////////////////////
//////////////归并排列
void MERGE(int low, int mid, int high)//
{
int temp = low;
int a = low, b = mid + 1;
while (temp <= high)
{
if (a == mid + 1)
{
for (int i = b; b <= high; b++)
{
B[temp++] = A[b];
}
break;
}
if (b == high + 1)
{
for (int i = a; a <= mid; a++)
{
B[temp++] = A[a];
}
break;
}
if (A[a] < A[b])
{
B[temp++] = A[a];
a++;
}
else
{
B[temp++] = A[b];
b++;
}
}
for (int i = 0; i < 10; i++)
{
A[i] = B[i];
}
}
void mergesort(int low, int high)//
{
int mid;
if (low < high)
{
mid = (low + high) / 2;
mergesort(low, mid);
mergesort(mid + 1, high);
MERGE(low, mid, high);
}
}////////////////////////////////////////////
//以下为快速排列
int  SPLIT(int low, int high)
{
int w, temp;
int i = low, x = C[low];
for (int j = low + 1; j <= high; j++)
{
if (C[j] <= x)
{
i++;
if (i != j)
{
temp = C[i];
C[i] = C[j];
C[j] = temp;
}
}
}
temp = C[low];
C[low] = C[i];
C[i] = temp;
w = i;
return w;
}
void quicksort(int low, int high)
{

int w;
if (low < high)
{
w = SPLIT(low, high);
quicksort(low, w - 1);
quicksort(w + 1, high);
}
}
/////////////////////////////////////////
int main()
{
int m, k = 1, mtime = 0, qtime = 0;
cout << "请输入要比较的次数：" << endl;
cin >> m;
int n = size;
while (m--)
{
cout << "----------------------------------------" << endl;
cout << "第 " << k++ << " 次比较结果：" << endl;
generation();
clock_t start_time = clock();
mergesort(0, n - 1);
/*	for (int i = 0; i < n; i++)
{
cout << " " << A[i];
}*/
clock_t end_time = clock();//获取时间，精确到ms;
mtime += (end_time - start_time);
cout << "mergesort 's running time is: " << end_time - start_time << "ms" << endl;//输出运行时间

clock_t start_time1 = clock();
quicksort(0, n - 1);
/*for (int i = 0; i < 10; i++)
{
cout << " " << C[i];
}*/
clock_t end_time1 = clock();
qtime += (end_time1 - start_time1);
cout << "quicksort's running time is: " << end_time1 - start_time1 << "ms" << endl;//输出运行时间
}
cout << endl << "=========================================" << endl;
cout << "mergesort 's average running time is: " << mtime / k << endl;
cout << "quicksort 's average running time is: " << qtime / k << endl;
return 0;
}

《算法》实验一归并排序与快速排序 时间的比较