Illustration
Reference Code
void selectSort(int A[], int lens){ if (A == NULL || lens <=0) return; for (int i = 0; i < lens; ++i) { int minp = i; for (int j = i+1; j < lens; ++j) { if (A[j] < A[minp]) minp = j; } swap(A[minp], A[i]); }}
Test
#include <iostream>using namespace std;void selectSort(int A[], int lens){ if (A == NULL || lens <=0) return; for (int i = 0; i < lens; ++i) { int minp = i; for (int j = i+1; j < lens; ++j) { if (A[j] < A[minp]) minp = j; } swap(A[minp], A[i]); }}void tranverse(int A[], int lens){ for (int i = 0; i < lens; ++i) cout << A[i] << " "; cout << endl;}int main(){ int A[] = {5, 2, 9, 1, 3, 2, 2, 7}; int lens = sizeof(A) / sizeof(*A); tranverse(A, lens); selectSort(A, lens); tranverse(A, lens);}View code
Performance
Space complexity: O (1)
Time Complexity: Best, worst, average total O (n2)
Stability
Unstable. Case: 2, 4 *, 3 before sorting. After sorting, 2, 3, 4 *, 4.
Simple selection and sorting