[英]Selection Sort Comparisons
我必須跟蹤此選擇排序中的所有比較,但是當我只返回1000列表中的值中的1時。我不確定我是否正確實現了它,但是我確定我正確放置了比較計數/ 。 通常,選擇排序具有固定數量的鍵比較,但是我們的講師禁止使用公式來跟蹤它們。 我很好奇為什么此輸出不斷返回:
comp = 1
swap = 1
template <class elemType>
void selectionSort(elemType list[], int length)
{
int loc, minIndex;
int first;
int last, second;
int swaps =0;
int comp = 0;
minIndex = first;
for (loc = 0; loc < length; loc++)
{
comp+=1;
for(loc = first +1; loc<=last; loc++)
{
comp+=1;
if(list[loc]<list[minIndex])
minIndex=loc;
comp+=1;
}
elemType temp;
temp= list[first];
list[first]= list[second];
list[second] = temp;
swaps+=1;
}
// comp = (length *(length-1)/2);
cout<<"swaps= "<<swaps<<endl;
cout<<"comps= "<<comp<< endl;
}
任何想法表示贊賞
我猜您的排序本身不起作用。 您需要正確初始化last
, first
和second
變量(特別是last
),然后移動(遞增)它們。
由於您的last
變量的默認0
,因此由於您想要的第二個for循環中的loc<=last
條件,它不會執行迭代。 我認為您需要將其初始化為:
last = length-1;
還有一個問題:在兩個循環中,您使用的索引變量是loc
。 我認為您需要使用兩個不同的變量。
for (loc = 0; loc < length; loc++)
{
comp+=1;
for(loc = first +1; loc<=last; loc++)
{
修復邏輯以便執行完整排序后,您將獲得正確的計數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.