[英]c++ can't get selection sort to work properly
我試圖了解排序算法,因此根據google的示例/說明,我編寫了以下代碼。 代碼有80%的時間有效。 有時它無法正確排序,我看不出原因。
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void setArray( int *, const int & );
void selectionSorting( int *, const int & );
int main()
{
int numOfElem;
cout << "Num of array elements: ";
cin >> numOfElem;
cout << '\n';
int array[numOfElem];
setArray(array, numOfElem);
selectionSorting(array, numOfElem);
cout << '\n';
return 0;
}
void setArray( int *array, const int & numOfElem ){
srand(time(0));
cout << "Original array: " << '\n';
for (int i=0; i<numOfElem; i++){
array[i] = rand()%30;
cout << array[i] << ' ';
}
cout << '\n';
}
void selectionSorting( int *array, const int &numOfElem ){
int eff_size, swap;
int maxpos = 0;
for (eff_size = numOfElem; eff_size>1; eff_size--){
// loop searching for a position of largest number in the array
for (int i=0; i<eff_size; i++){
maxpos = array[i] > array[maxpos] ? i : maxpos;
}
swap = array[maxpos];
array[maxpos] = array[eff_size-1];
array[eff_size-1] = swap;
}
cout << "Selection Sorting: " << '\n';
for (int i=0; i<numOfElem; i++){
cout << array[i] << ' ';
}
}
輸出示例:
Num of array elements: 5
Original array:
7 17 1 12 25
Selection Sorting:
1 7 17 25 12
我看不到任何排序失敗的模式-排序失敗在不同的地方,如果有重復的數字,無論我提供多少個數字,等等...
在外部循環的每次迭代中(在eff_size
),您都應將maxpos
為0。否則, maxpos
會超出排序的有效部分(如果最大元素位於有效部分的最后,則發生這種情況,即maxpos==effsize
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.