冒泡排序的实现

    function CArray(numElements) {
        this.dataStore = [];
        this.numElements = numElements;
        this.prints = prints;
        this.setData = setData;
        this.bubbleSort = bubbleSort;
        //this.selectionSort = selectionSort;
    }
    function setData() {
        for ( var i = 0; i < this.numElements; ++i) {
            this.dataStore[i] = Math.floor(Math.random()
                    * (this.numElements + 1));
        }
    }
    function prints() {
        for ( var i = 0; i < this.dataStore.length; ++i) {
            document.write(this.dataStore[i] + " ");
            if (i > 0 & i % 10 == 0) {
                document.write("<br />");
            }
        }
    }
    function swap(arr, index1, index2) {
        var temp = arr[index1];
        arr[index1] = arr[index2];
        arr[index2] = temp;
    }
    var numElements = 100;
    var myNums = new CArray(numElements);
    myNums.setData();

    function bubbleSort() {//像金鱼吐泡泡一样逐渐将较大的数移至最右边
        var numElements = this.dataStore.length;
        for ( var outer = numElements; outer >= 2; --outer) {//初始指针在最右边
            for ( var inner = 0; inner <= outer - 1; ++inner) {
                //初始指针在最左边,第一次 大循环实现将最大的数移至最右边
                if (this.dataStore[inner] > this.dataStore[inner + 1]) {
                    swap(this.dataStore, inner, inner + 1);//交换两数的位置
                    //从左到右依次两两比较
                }
            }
        }
    }
    myNums.bubbleSort();
    myNums.prints();

 

posted @ 2016-04-14 19:34  绯乐  阅读(153)  评论(0编辑  收藏  举报