2013-09-23 18 views
0

我試圖做一個插入/合併排序程序,並且都需要接受高達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; 
} 
+1

什麼操作系統中找不到? – Duck

+0

6小時?這是一項任務嗎?如果是這樣,也許你做的事情非常錯誤。 –

回答

0

根據您的OS系統上,你可以設立專門的環境爲你的程序在運行等,如果時間太長(或其他條件),則程序將終止。或者,你可以產生一個線程,只要你想要倒計時。如果完成並且主線程仍在運行,則可以從該處終止程序。

0

你可以與ctime模塊做到這一點很容易我猜:

#include <ctime> 
#define HALF_HOUR 60 * 30 
using namespace std; 
... 
clock_t start = clock(); 
clock_t now; 
int i, j, tmp; 
for (i = 1; i < length; i++) { 
    j = i; 
    while (j > 0 && arr[j - 1] > arr[j]) { 
      now = clock(); 
      if ((now - start)/CLOCKS_PER_SEC) >= HALF_HOUR) 
      { 
       cout << "Insert sort timed out." << endl; 
       return; 
      } 
      tmp = arr[j]; 
      arr[j] = arr[j - 1]; 
      arr[j - 1] = tmp; 
      j--; 
    } 
0

最簡單的方法是實現一個定時回調函數。該功能將在指定的時間間隔後被調用,您可以退出該功能中的程序。關於如何實現它

的更多信息,可以在下面的鏈接

c++ Implementing Timed Callback function

相關問題