Javascript实现插入排序

javascript,sort
Thu Aug 16 2018 12:08:11 GMT+0000 (UTC)
function InsertSort1(arr){
	for(var i = 1; i < arr.length; i++){
		for(var j = 0; j < i; j++){
			debugger;
			var tempj = arr[j];
			var tempi = arr[i];
			if(tempj > tempi){
				arr.splice(j,0,arr[i]); //在数组j处添加一个元素arr[i]
				arr.splice(i+1,1); //删除数组从i+1开始的1个元素
			}
			console.log(arr);
		}
	}
	return arr;
}
var arr = [ 5,9,8,2,4]
var result = InsertSort1(arr); 


function InsertSort2(arr){
	for(var i = 0; i < arr.length; i++){
		let value = arr[i];// store the current item value so it can be placed right
		debugger;
		for(var j = i - 1; j > -1 && arr[j] > value; j--){
			// loop through the items in the sorted array (the items from the current to the beginning)
      // copy each item to the next one
			arr[j+1] = arr[j];
		}
		console.log(arr)
		arr[j+1] = value;// the last item we've reached should now hold the value of the currently sorted item
		console.log('----------')
		console.log(arr);
	}
	return arr;
}
var arr = [ 5,9,8,2,4]
var result = InsertSort2(arr);