#include <iostream>
using namespace std;
//入口参数:数组, 数组元素个数 template<typename T> void selectionSort(T arr[], int size) { int j; T temp; int minIndex; //每次查找到的最小元素下标
for (int i=0; i<size-1; i++) { minIndex = i; //找到最小的元素,用minIndex保存下标 for (j=i+1; j<size; j++) { if (arr[minIndex] > arr[j]) { minIndex = j; } }
if (i != minIndex) { temp = arr[i]; arr[i] = arr[minIndex]; arr[minIndex] = temp; } } }
int main() { int array[] = {10, 20, 50, 5, 654, 24, 128, 25};
cout << "Before sort: "; for (int i=0; i<8; i++) { cout << array[i] << " "; }
selectionSort(array, 8);
cout << endl << "After sort: "; for (i=0; i<8; i++) { cout << array[i] << " "; }
cout << endl;
return 0; } 
|