voidinsertion_sort(int arr[], int len){
int i,j,key;
for (i=1;i<len;i++){
key = arr[i];
j=i-1;
while((j>=0) && (arr[j]>key)) {
arr[j+1] = arr[j];
j--;
}
arr[j+1] = key;
}
}
2.Go代码实现
go
1
2
3
4
5
6
7
8
9
10
11
12
funcinsertionSort(arr []int) []int {
for i :=range arr {
preIndex := i -1 current := arr[i]
for preIndex >=0&& arr[preIndex] > current {
arr[preIndex+1] = arr[preIndex]
preIndex -=1 }
arr[preIndex+1] = current
}
return arr
}
3.JS代码实现
js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function insertionSort(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;
}
评论