几种经典排序算法的JS实现方法

前端之家收集整理的这篇文章主要介绍了几种经典排序算法的JS实现方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

一.冒泡排序

0; i--) { //用于缩小范围 for (var j = 0; j < i; j++) { //在范围内进行冒泡,在此范围内最大的一个将冒到最后面 if (array[j] > array[j+1]) { var temp = array[j]; array[j] = array[j+1]; array[j+1] = temp; } } console.log(array); console.log("-----------------------------"); } return array; }

var arr = [10,9,8,7,6,5,11,3];
var result = BubbleSort(arr);
console.log(result);
/*
[ 9,10,3,11 ]

[ 8,11 ]

[ 7,11 ]

[ 6,11 ]

[ 5,11 ]

[ 3,11 ]
*/

二.选择排序

var arr = [ 1,100,90,65,4,2,4 ];
var result = SelectionSort(arr);
console.log(result);
/*
[ 1,4 ]

[ 1,90 ]

[ 1,100 ]

[ 1,100 ]
*/

三.插入排序

= 0; j--) { if (insert < array[j]) { //要插入的项比它小,往后移动 array[j+1] = array[j]; index = j; } } array[index] = insert; console.log(array); console.log("-----------------------"); } return array; }

var arr = [100,80,62,1,39];
var result = InsertionSort(arr);
console.log(result);
/*
[ 90,39 ]

[ 80,39 ]

[ 62,39 ]

[ 8,39 ]

[ 1,39,100 ]

[ 1,100 ]
*/

四.希尔排序

0) { for (var i = gap; i < length; i++) { var insert = array[i]; var index = i; for (var j = i; j >= 0; j-=gap) { if (insert < array[j]) { array[j+gap] = array[j]; index = j; } } array[index] = insert; } console.log(array); console.log("-----------------------"); gap = Math.round(gap/2 - 0.1); } return array; }

var arr = [ 13,14,94,33,82,25,59,23,45,27,73,10 ];
var result = ShellSort(arr);
console.log(result);
/*
[ 13,94 ]

[ 13,94 ]

[ 10,13,94 ]
*/

五.归并排序

function merge(left,right) {
console.log(left);
console.log(right);
var a = new Array();
while (left.length > 0 && right.length > 0) {
if (left[0] <= right[0]) {
var temp = left.shift();
a.push(temp);
} else {
var temp = right.shift();
a.push(temp);
}
}
if (left.length > 0) {
a = a.concat(left);
}
if (right.length > 0) {
a = a.concat(right);
}
console.log(a);
console.log("-----------------------------");
return a;
}

var arr = [ 13,10 ];
var result = MergeSort(arr);
console.log(result);
/*
[ 13 ]
[ 14 ]
[ 13,14 ]

[ 94 ]
[ 33 ]
[ 33,94 ]

[ 13,14 ]
[ 33,94 ]
[ 13,94 ]

[ 82 ]
[ 25 ]
[ 25,82 ]

[ 59 ]
[ 94 ]
[ 59,94 ]

[ 25,82 ]
[ 59,94 ]
[ 25,94 ]

[ 65 ]
[ 23 ]
[ 23,65 ]

[ 45 ]
[ 27 ]
[ 27,45 ]

[ 23,65 ]
[ 27,45 ]
[ 23,65 ]

[ 73 ]
[ 25 ]
[ 25,73 ]

[ 39 ]
[ 10 ]
[ 10,39 ]

[ 25,73 ]
[ 10,39 ]
[ 10,73 ]

[ 23,65 ]
[ 10,73 ]

[ 13,94 ]
[ 10,94 ]

[ 10,94 ]
*/

六.快速排序

var arr = [ 8,4 ];
var result = QuickSort(arr);
console.log(result);
/*
[ 5,10 ]

[ 4,5 ]

[ 2,4 ]

[ 2,4 ]

[ 10,65 ]

[ 90,100 ]

[ 65,90 ]

[ 2,100 ]
*/

以上这篇几种经典排序算法的JS实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程之家。

猜你在找的JavaScript相关文章