functioninsertionSort(arr) { var len = arr.length; var preIndex, current; for (var i = 1; i < len; i++) { preIndex = i - 1; current = arr[i]; while(preIndex >= 0 && arr[preIndex] > current) { arr[preIndex+1] = arr[preIndex]; preIndex--; } arr[preIndex+1] = current; } return arr; }
4. Python 代码实现
1 2 3 4 5 6 7 8 9
definsertionSort(arr): for i in range(len(arr)): preIndex = i-1 current = arr[i] while preIndex >= 0and arr[preIndex] > current: arr[preIndex+1] = arr[preIndex] preIndex-=1 arr[preIndex+1] = current return arr
5. Go 代码实现
1 2 3 4 5 6 7 8 9 10 11 12
funcinsertionSort(arr []int) []int { 4for i := range arr { 44preIndex := i - 1 44current := arr[i] 44for preIndex >= 0 && arr[preIndex] > current { 444arr[preIndex+1] = arr[preIndex] 444preIndex -= 1 44} 44arr[preIndex+1] = current 4} 4return arr }