Skip to content

Instantly share code, notes, and snippets.

@vace
Last active June 24, 2016 05:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vace/d128a836c0064ac01628a9d10853a887 to your computer and use it in GitHub Desktop.
Save vace/d128a836c0064ac01628a9d10853a887 to your computer and use it in GitHub Desktop.
算法-插入排序实现
function insertionSort(arr){
var len = arr.length,index = 0,val
for(var j = 1;j < len ; j++){
val = arr[j]
index = j - 1;
while(index >= 0 && val < arr[index]){
arr[index+1] = arr[index]
index = index - 1
}
arr[index+1] = val
}
return arr
}
<?php
function insertionSort($arr){
$len = count($arr);
for($j = 1;$j < $len ; $j++){
$val = $arr[$j];
$index = $j - 1;
for($index = $j - 1; $index >= 0; $index--){
if($val > $arr[$index]){
break;
}
$arr[$index+1] = $arr[$index];
}
$arr[$index+1] = $val;
}
return $arr;
}
def insertionSort(arr):
for index in range(1,len(arr)):
val = arr[index]
prev = index - 1
while prev >= 0 and arr[prev] > val:
arr[prev + 1] = arr[prev]
prev = prev - 1
arr[prev + 1] = val
return arr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment