簡單選擇排序演算法(泛型)
阿新 • • 發佈:2019-02-04
main.cpp
#include "SelectSort.h"
int main()
{
int r[8] = {0,49,27,65,97,76,13,38};
SelectSort(r, 7);
return 0;
}
SelectSort.h
#include <iostream> using namespace std; template <class T> void SelectSort(T r[], T n) //簡單選擇排序演算法 { for(int i = 1; i < n; i++) { int index = i; for(int j = i + 1; j <= n; j++) if(r[j] < r[index]) index = j; if(index != i) //r[0]用作交換操作的暫存單元 { r[0] = r[i]; r[i] = r[index]; r[index] = r[0]; } } for(int m = 1; m <= n; m++) cout << r[m] << " "; cout << endl; }
結果:13 27 38 49 65 76 97