代码改变世界

用JS实现的常见几种排序算法

2015-07-07 15:55  zdwzdwzdw  阅读(223)  评论(0编辑  收藏  举报

1.快速排序法

function quickSort(a) {
                if (a.length <= 1) {
                        return a;
                }
                var midLength = Math.floor(a.length / 2);
                var midValue = a.splice(midLength,1);
                var left = [];
                var right = [];
                for (var i = 0; i < a.length; i++) {
                        if (a[i] < midValue) {
                                left.push(a[i]);
                        } else {
                                right.push(a[i]);
                        }
                }
                return quickSort(left).concat(midValue,quickSort(right));
        }
        console.log(quickSort([1,5,3,6,2,4,0]));

 

2.插入排序法

function insertSort(a) {
                var length = a.length;
                var sortArray;
                for (var i = 1; i < length; i++) {
                        for (var j = 0; j < i ; j++) {
                                if (a[i] < a[j]) {
                                        sortArray = a[i];
                                        a[i] = a[j];
                                        a[j] = sortArray;
                                }
                        }
                }
                return a;
        }
        console.log(insertSort([0,6,5,3,4,2,1,7]));

 

3.冒泡排序

function bubbleSort(a) {
                var length = a.length;
                var sortArray;
                for (var i = 0; i < length-1; i++) {
                        for (var j = 0; j < length-i-1 ; j++) {
                                if (a[j] > a[j+1]) {
                                        sortArray = a[j];
                                        a[j] = a[j+1];
                                        a[j+1] = sortArray;
                                }
                        }
                }
                return a;
        }
        console.log(bubbleSort([2,1,3,6,5,4,7,0]));

 

4.选择排序

 function selectSort(a) {
                for (var i = 0; i < a.length; i++) {
                        var min = a[i];
                        var k = i;
                        for (var j = i + 1; j < a.length; j++) {
                                if (min > a[j]) {
                                        min = a[j];
                                        k = j;
                                }
                        }
                        a[k] = a[i];
                        a[i] = min;
                }
                return a;
        }
        console.log(selectSort([5,1,4,0,3,2,7,6]));