我試圖做一個插入/合併排序程序,並且都需要接受高達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;
}
什麼操作系統中找不到? – Duck
6小時?這是一項任務嗎?如果是這樣,也許你做的事情非常錯誤。 –