javascript 冒泡排序

<script>
    var arr = [3, 1, 4, 6, 5, 7, 2];

    function bubbleSort(arr) {
        var len = arr.length;
        for (var i = len; i >= 2; --i) {
            for (var j = 0; j < i - 1; j++) {
                if (arr[j + 1] < arr[j]) {
                    var temp;
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        return arr;
    }

    function bubbleSort2(arr) {
        var len = arr.length;
        for (var i = 0; i <= len - 1; i++) {
            for (var j = 0; j <= len - i; j++) {
                if (arr[j + 1] < arr[j]) {
                    var temp;
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        return arr;
    }

    console.log(bubbleSort(arr));
    console.log(bubbleSort2(arr));
</script>
posted @ 2017-05-17 10:34  winyh  阅读(156)  评论(0编辑  收藏  举报