实现逻辑
① 第一轮从下标为 1 到下标为 n-1 的元素中选取最小值,若小于第一个数,则交换
② 第二轮从下标为 2 到下标为 n-1 的元素中选取最小值,若小于第二个数,则交换
③ 依次类推下去……
void print_array(int a[], int n){for (int i = 0; i < n; ++i){cout << a[i] << " ";}cout << endl;
}void selectSort(int arr[], int nSize)
{for (int i = 0; i < nSize - 1; ++i){int nMin = i;for (int j = i + 1; j < nSize; ++j){if (arr[nMin] < arr[j]){nMin = j;}}if (nMin != i){int nTemp = arr[nMin];arr[nMin] = arr[i];arr[i] = nTemp;}}
}int main(){int arr[] = {10, 8, 11, 7, 4, 12, 9, 6, 5, 3};int len = sizeof(arr)/sizeof(arr[0]);int newArray[10] = {0};cout << "排序前:";print_array(arr, len);selectSort(arr, len);cout << "排序后:";print_array(arr, len);return 0;
}
输出结果: