[英]Best case , Worst case , Random data input for insertion sort algorithm?
這是我編寫的用於初始輸入隨機數然后使用插入排序方法對其進行排序的代碼。
#include<iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main(void)
{
int array[10];
srand (time(0));
for (int i = 0; i < sizeof(array)/sizeof(array[0]); i++ )// inputting values into array[10]
{
array[i] = 1 + (rand()%100); //any random number between 1 - 100
}
cout <<" Before sorting " << " ---" <<endl;
for (int i = 0; i < sizeof(array)/sizeof(array[0]); i++ )// printing the values
{
cout << array[i]<< endl;
}
int key ;
int t;//for future purpose
int compcount = 0;//to keep track of comparisons
for (int j = 1; j<sizeof(array)/sizeof(array[0]);j++)
{
key = array[j];//assign to second element initially
t = j-1;//assign to first element initially
while (j > 0 && array[t]>key)
{
array[t+1] = array[t];//moving array if bigger than next element
t = t-1;
compcount++;
}
array[t+1] = key;
}
cout << " After sorting" << " --- " <<endl;
for (int i = 0; i < sizeof(array)/sizeof(array[0]); i++ )
{
cout << array[i]<< endl;
}
cout << "comparison count is " << compcount << endl;
system ("pause");
return 0;
}
老實說,我有一個項目,它要求運行算法以獲得最佳,最差和隨機輸入,並計算關鍵比較的數量(我相信在此代碼中是“compcount”)
現在隨機輸入對此有意義。 當我使用“已經排序”的數字數組(最好的情況)進行另一個代碼時,關鍵比較的數量為0.能否有人了解最壞情況是否與此完全相反? 如果是這種情況我嘗試這樣做,但我只有32個比較,數組的大小為32。
很抱歉這個問題很長。 最壞情況輸入應該有(n ^ 2-n)/ 2個比較對嗎? 最好的情況應該是n-1,因為只有第一個元素會遍歷整個列表並確認它已經排序。我如何在代碼中得到它?
您正在進行比較作為while條件的一部分,這意味着您只計算成功的比較,這就是為什么您的最佳案例結果是錯誤的。 compcount ++也應該在while循環之上。
編輯:
compCount++;
while (t >= 0 && array[t] > key)
{
array[t+1] = array[t];//moving array if bigger than next element
t = t-1;
if (t >= 0) // This is a hack to ensure that 't >= 0' will pass
compCount++; // and another comparison will happen
}
你的程序中有一個錯誤
while (j > 0 && array[t]>key)
應該
while (t >= 0 && array[t]>key)
除此之外,它適用於反向排序輸入。 這確實是最糟糕的情況,結果清楚地表明了這一點。
你的結果是n-1,但這是一個小問題。 有關解決方案,請參閱@ Mranz的答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.