用JS完成的罕见几种排序算法

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 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]));

3.插入排序

        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]));

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]));
    原文作者:zzzddd
    原文地址: https://segmentfault.com/a/1190000003934420
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞