选择排序的思想:每次都从未排序的序列中选出最大或最小的元素,放到已排好序的前部或者后部。
程序:
#include <iostream>
using namespace std;
void SelectSort(int a[], int length) {
for (int i = length - 1; i > 0; i--) {
int IndexOfMax = i;
int j = 0;
for (j = 0; j < i; j++) {
//if (a[j] > a[IndexOfMax]) { IndexOfMax = j;}
IndexOfMax = (a[j] > a[IndexOfMax]) ? j : IndexOfMax;
}
//选择排序和插入排序的区别:未排序的序列是否需要移动?
//需要移动的是插入排序,不需要移动的是选择排序。
int temp = a[j];//j = i
a[j] = a[IndexOfMax];
a[IndexOfMax] = temp;
}
}
int main() {
int a[10] = { 10, 13, 8, 6, 12, 15, 2, 20, 18, 28 };
int length = 10;
//BubbleSort(a, length);
//QuickSort(a, 0, length - 1);
//InsertSort(a, length);
SelectSort(a, length);
//HeapSort(a, length);
//MergeSort(a, length);
for (int i = 0; i < 10; i++) {
cout << a[i] << " ";
}
cout << endl;
return 0;
}
输出结果:
复杂度分析:未完待续