0
我幾乎完成了我的代碼,但我需要幫助定時器的泡沫排序和基數排序。時間總是在零,我嘗試了一切,但它總是結束爲零。代碼有問題嗎?或我正在使用的計時器的類型。泡沫和基數排序測試
更新...所以我現在固定的時間即時通訊工作排序測試,以確定如果函數排序陣列...這是我有,它仍然iffy。打印時它開始顯示多個「未排序」和「已排序」。
#include <iostream>
#include <cstdlib>
#include <ctime>
using std::cout;
using std::cin;
using std::endl;
int const temp = 10000;
void bubbleSort (int array [ temp ]);
void radixSort (int array [ temp ]);
int main ()
{
int A1;
int array [ temp ];
char a = '\0';
cout << "\nWould You Like To Perform Bubble and Radix Test? (y/n): ";
cin >> a;
if (a == 'y' || a == 'Y')
{
srand ((unsigned) time (0));
for (size_t i = 0; i < temp; i++)
{
A1 = (rand () % temp) + 1;
array [ i ] = A1;
}
cout << "\n-- Please Wait For Result --" << endl;
bubbleSort (array);
radixSort (array);
}
else
{
}
return 0;
}
void bubbleSort (int array [ temp ])
{
int temp1;
time_t start, end;
clock_t start = clock ();
for (int i = 0; i < temp - 1; i++)
{
for (int j = 0; j < temp - i - 1; j++)
{
if (array [ j ] > array [ j + 1 ])
{
temp1 = array [ j ];
array [ j ] = array [ j + 1 ];
array [ j + 1 ] = temp1;
}
}
}
for (int s = 1; s < temp; ++s)
{
if (array [ s ] > array [ s - 1 ])
{
cout << "sorted" << endl;
}
else
{
cout << "not sorted" << endl;
}
}
clock_t end = clock ();
printf ("Sorting Time: %f seconds\n", (double) (end - start)/1000000);
}
void radixSort (int array [ temp ])
{
int mx = array [ temp ];
int temp1;
clock_t start = clock ();
for (int i = 1; i < temp; i++)
{
if (array [ i ] > mx)
{
mx = array [ i ];
for (int j = 1; (mx/j) > 0; j *= 10)
{
int out [ temp ]; //output array
int k, count [ 10 ] = { 0 };
for (k = 0; k < temp; k++)
{
count [ (array [ k ]/i) % 10 ]++;
}
for (k = 1; k < 10; k++)
{
count [ k ] += count [ k - 1 ];
}
for (k = i -1; k >= 0; k--)
{
out [ count [ (array [ k ]/i) % 10 ] - 1 ] = array [ k ];
count [ (array [ k ]/i) % 10 ] --;
}
for (k = 0; k < temp; k++)
{
array [ k ] = out [ k ];
}
}
}
}
for (int s = 1; s < temp; ++s)
{
if (array [ s ] > array [ s - 1 ])
{
cout << "sorted" << endl;
}
else
{
cout << "not sorted" << endl;
}
}
clock_t end = clock ();
printf ("Sorting Time: %f seconds\n", (double) (end - start)/1000000);
}
'temp'對於數組的'size'來說是一個令人難以置信的糟糕名字。 – ooga
'time_t'('time'的返回值)通常具有一秒的分辨率。所以如果運行時間不到一秒鐘,你會得到零的時間。您應該使用'時鐘'功能。 – ooga
中途不要改變你的問題。問一個新問題。 – Matt