functionMySelectionSort() { this.sort = function(array) { for (var i = 0; i < array.length - 1; i++) { var min = i; for (var j = i + 1; j < array.length; j++) { if (array[j] < array[min]) { min = j; } } if (i != min) { var temp = array[i]; array[i] = array[min]; array[min] = temp; } } return array; } }
var sorter = new MySelectionSort(); var notSortedArr = [15, 8, 5, 12, 10, 1, 16, 9, 11, 7, 20, 3, 2, 6, 17, 18, 4, 13, 14, 19]; var sortedArr = sorter.sort(notSortedArr); console.log(sortedArr);
下面是ruby的实现
1 2 3 4 5 6 7 8 9 10 11 12 13
defmy_selection_sort(array) 0.upto(array.size - 1) do |i| min = i (i+1).upto(array.size - 1) do |j| min = j if array[j] < array[min] end array[i], array[min] = array[min], array[i] if i != min end end
publicclassMySelectionSort{ privatestaticvoidsort(int[] array){ for (int i = 0; i < array.length - 1; i++) { int min = i; int j = i + 1; for (; j < array.length; j++) { if (array[j] < array[min]) { min = j; } } if (min != i) { int temp = array[i]; array[i] = array[min]; array[min] = temp; } } }