我正在尝试制作一个插入/合并排序程序,两者都做,它需要接受多达 1000 万个系列长数组的输入。对于合并排序,这很好,排序需要几秒钟,但根据我的朋友的说法,插入应该需要 6 个多小时。我想在程序中设置一个计时器,让它在工作 30 分钟后停止,并且没有以某种方式完成排序,但我不知道如何,或者我会把它放在哪里。
这是我的主要方法和插入排序的代码,因为它是唯一需要计时器的代码。有人知道该怎么做或从哪里开始吗?
void insertionSort(int arr[], int length) {
int i, j, tmp;
for (i = 1; i < length; i++) {
j = i;
while (j > 0 && arr[j - 1] > arr[j]) {
tmp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = tmp;
j--;
}
}
}
int main()
{
srand (time(0));
long x;
cout << "how long will the array be?\n" <<
"10, 100, 1000, 10000, 100000, 1000000, or 10000000?" << endl;
cin >> x;
switch(x){
case 10:
x = 10;
break;
case 100:
x = 100;
break;
case 1000:
x = 1000;
break;
case 10000:
x = 10000;
break;
case 100000:
x = 100000;
break;
case 1000000:
x = 1000000;
break;
case 10000000:
x = 10000000;
break;
default:
cout << "Error, incorrect number entered, please try again!" << endl;
}
static int ar[10000000];
for(int i = 0; i < x; i++){
ar[i] = rand() % 100000001;
}
int c= 0;
cout << "which sorting method would you like to use?\n" <<
"Insertion(1), merge(2), or quick(3)? \nPlease enter the number beside the one you want to use" << endl;
cin >> c;
if(c == 1){
insertionSort(ar, x);
}
else if(c==2){
for (int i = 1; i < x; i *= 2) {
for (int j = 0; j < x- i; j += 2*i) {
int iEnd2 = (2*i < x - j) ? 2*i : x - j;
Merge(&(ar[j]), i, iEnd2);
}
}
} else if(c==3){
quickSort(ar,0,x-1);
} else{
cout << "You did not enter a correct number, please try again" << endl;
}
for(int i = 0; i < x; i++){
cout << ar[i] << endl;
}
return 0;
}