问题描述
- 新人求助!记录程序时间出错
-
#include
#include
#include
#include"sort.h"
using namespace std;
int main()
{
int choice, n, i, j;
DWORD start, end;
while(1)
{
cout << "输入数据的方式:" << endl;
cout << "1、手动输入" << endl;
cout << "2、系统自动产生" << endl;
cout << "输入方式序号:" << endl;
cin >> choice;if (choice == 1) { cout << "排序的元素个数:" << endl; cin >> n; int *a = new int[n]; int *b = new int[n]; int *temp = new int[n]; cout << "要排序的元素:" << endl; for (i = 0; i < n; i++) { cin >> a[i]; b[i] = a[i]; } cout << "快排结果:" << endl; Quicksort(a, 0, n - 1); for (i = 0; i < n; i++) cout << a[i] << " "; cout << endl; cout << "归并结果:" << endl; Mergesort(b, 0, n - 1); for (i = 0; i < n; i++) cout << b[i] << " "; cout << endl; } else if (choice == 2) { cout << "下面将随机产生10组数据:" << endl; for (i = 1; i <= 10; i++) { cout << "#" << i << endl; int *a = new int[10000 * i]; int *b = new int[10000 * i]; int *temp = new int[10000 * i ]; for (j = 0; j < 10000 * i; j++) { a[j] = rand() % 100000; b[j] = a[j]; } start = GetTickCount(); Quicksort(a, 0, 10000 * i - 1); end = GetTickCount(); cout << "快速排时间:" << end - start << "ms" << endl; start = GetTickCount(); Mergesort(b, 0, 10000 * i - 1); end = GetTickCount(); cout << "归并排时间:" << end - start << "ms" << endl; } } else break; } system("pause"); return 0; 程序中choice==1是用来测试两个排序算法有没有正确排序的,经测没问题,可是到随机生成后就有问题了,输出的时间很不对劲... 另外,别人的程序在自己电脑上没问题,到我的电脑就出现同样问题了!!!!! 图片补在下面
解决方案
解决方案三:
计算机的时间精度也就是几十ms级别。你的数据量太小了。把数据扩大100倍。
解决方案四:
你申请了内存之后要释放的啊,你这样每申请一次都会有内存泄露,不应该是关掉重启出错,理论上运行时间久点,最后a,b会没有内存申请返回NULL,时间就不可预知了,所以排序时间会变得混乱,你在 for (i = 1; i <= 10; i++)这个循环的末尾加上delete []a; delete[]b;如下:
for (i = 1; i <= 10; i++)
{
cout << "#" << i << endl;
int *a = new int[10000 * i];
int *b = new int[10000 * i];
int *temp = new int[10000 * i ];
for (j = 0; j < 10000 * i; j++)
{
a[j] = rand() % 100000;
b[j] = a[j];
}
start = GetTickCount();
Quicksort(a, 0, 10000 * i - 1);
end = GetTickCount();
cout << "快速排时间:" << end - start << "ms" << endl;
start = GetTickCount();
Mergesort(b, 0, 10000 * i - 1);
end = GetTickCount();
cout << "归并排时间:" << end - start << "ms" << endl;
delete []a;
delete []b;
}
时间: 2024-11-01 01:39:56