Heya我想在單向鏈表上實現選擇排序算法,我知道代碼中存在一些問題,但儘管我的鏈表包含數字7 1 2 6運行後的輸出是7777。任何幫助,將不勝感激。在單向鏈表上實現選擇排序
template<class Type>
void UnOrderedLinkedList<Type>::selectionSort()
{
nodeType<Type>* loc;
nodeType<Type>* minIndex;
nodeType<Type>* temp;
temp = first;
if(temp == NULL)
cerr<<"Cannot sort an empty list."<<endl;
else
if(temp->link == NULL)
cerr<<"List has only one item so it is already sorted."<<endl;
else
while(temp != NULL)
{
minIndex = minLocation(temp, last);
swap(temp, minIndex);
temp = temp->link;
}
}
template<class Type>
nodeType<Type>* UnOrderedLinkedList<Type>::minLocation(nodeType<Type>* first, nodeType<Type>* last)
nodeType<Type>* minIndex;
nodeType<Type>* other;
minIndex = first;
other = minIndex->link;
while(other != NULL)
{
if(minIndex->info > other->info)
{
minIndex = other;
other = other->link;
}
else
{
other = other->link;
}
}
return minIndex;
}
然後交換:
template<class Type>
void UnOrderedLinkedList<Type>::swap(nodeType<Type>* first, nodeType<Type>* second)
{
nodeType<Type>* temp;
temp->info = first->info;
first->info = second->info;
second->info = temp->info;
}
Joachim非常感謝你我的代碼現在完美的工作! :) – Didem