自行总结:从愈来愈小的选择区间中选择一个最小(大)的值,和选择区间最前面的值交换位置
,直到排序完成javascript
#include <iostream> using namespace std; void selectionSort(int arr[], int n){ // 一层循环,缩小寻找最小值的区间范围 for(int i = 0; i < n; i ++){ // 二层循环,寻找[i, n)区间里的最小值的index int minIndex = i; for( int j = i + 1; j < n; j ++ ){ if( arr[j] < arr[minIndex]) minIndex = j; } // 二层循环完毕,区间最小值和区间第一交换位置,放到区间最前面 // swap函数,进行交换 swap(arr[i], arr[minIndex]); } } int main() { int a[10] = {10,9,8,7,6,5,4,3,2,1}; selectionSort(a, 10); for ( int i = 0; i < 10; i ++ ) cout<<a[i]<<" "; cout<<endl; return 0; }
注:对于c++实现,整数,浮点和字符串数组可经过写泛型参数实现,而集合数组
则须要写类实现(之后再研究代码吧)java
function selectionSort(arr, n){ // 一层循环,缩小寻找最小值的区间范围 for(let i = 0; i < n; i++){ // 二层循环,寻找[i, n)区间里的最小值的index let minIndex = i; for(let j = i+1; j < n; j++){ if(arr[j]<arr[minIndex]){ minIndex = j; } } // 二层循环完毕,区间最小值和区间第一交换位置,放到区间最前面 // es6解构赋值,进行交换 [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]]; } return arr; } selectionSort([10,9,8,7,6,5,4,3,2,1],10);
selectionSort([10,9,8,7,6,5,4,3,2,1],10);
(10) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
selectionSort([5.5,4.5,3.5,2.5,1.1],5);
(5) [1.1, 2.5, 3.5, 4.5, 5.5]
selectionSort(['d','a','f','c','b'],5);
(5) ["a", "b", "c", "d", "f"]
注:对于js实现,整数,浮点和字符串数组均可通用,而集合数组
则取具体属性比较即可用ios