//从arr[1]开始,与前面的元素比较,小的放前面,大的放后面var Arr =[7,4,9,13,2,5,3,4];functioninsertionSort(arr){for(var i =1; i < arr.length; i++){var item = arr[i];//存放待插元素var j = i -1;//从待插元素前一个元素开始,向前遍历while(j >=0&& arr[j]> item){
arr[j +1]= arr[j];//如果大于待插元素,往后移
j--;}
arr[j +1]= item;}return arr;}
console.log(insertionSort(Arr));
方法4 希尔排序
var Arr =[7,4,9,13,2,5,3,4];functionshellSort(arr){var len = arr.length;var gap, i;for(gap = Math.floor(len /2); gap >0; gap = Math.floor(gap /2)){for(i = gap; i < len; i++){var temp = arr[i];var j = i - gap;while(j >=0&& arr[j]> temp){
arr[j + gap]= arr[j];
j = j - gap;}if(j != i - gap){
arr[j + gap]= temp;}}}return arr;}
console.log(shellSort(Arr))
方法5 快速排序
var Arr =[7,4,9,13,2,5,3,4];functionquickSort(arr){if(arr.length <=1){return arr;//递归终止条件}var pointIndex = Math.floor(arr.length /2);//基准点索引var point = arr.splice(pointIndex,1)[0];//splice返回删除的数组var left =[];var right =[];for(var i =0; i < arr.length; i++){if(arr[i]<= point){
left.push(arr[i]);}else{
right.push(arr[i]);}}returnquickSort(left).concat([point],quickSort(right))}
console.log(quickSort(Arr))
方法6 归并排序
var Arr =[7,4,9,13,2,5,3,4];functionmergeSort(arr){if(arr.length <=1){return arr;}var mid = Math.floor(arr.length /2);var left = arr.slice(0, mid);//slice返回所取数组的片段,splice返回的是删除的片段var right = arr.slice(mid);returnmerge(mergeSort(left),mergeSort(right));}functionmerge(left, right){var re =[];while(left.length >0&& right.length >0){if(left[0]<= right[0]){
re.push(left.shift());//shift删除数组第一个元素,并返回}else{
re.push(right.shift());}}return re.concat(left, right)}
console.log(mergeSort(Arr))