functionMyInsertionSort() { this.sort = function(array) { for (var i = 0; i < array.length; i++) { for (var j = i; j > 0; j--) { if (array[j-1] > array[j]) { var temp = array[j-1]; array[j-1] = array[j]; array[j] = temp; } else { break; } } } return array; } }
var sorter = new MyInsertionSort(); 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_insertion_sort(array) 0.upto(array.size - 1) do |i| j = i while j > 0and array[j-1] > array[j] array[j-1], array[j] = array[j], array[j-1] j = j - 1 end end end