数据结构与算法javascript描述(四) 冒泡排序

js实现冒泡排序

建一个数组类和一些封装了常规数组操作的函数:CArray
插入新数据, 显示数组数据及调用不同的排序算法。

  • CArray
/* CArray*/
function CArray(numElements) {
    this.dataStore = [];
    this.pos = 0;
    this.numElements = numElements;
    this.insert = insert;
    this.toString = toString;
    this.clear = clear;
    this.setData = setData;
    this.swap = swap;

    for ( var i = 0; i < numElements; ++i ) {
        this.dataStore[i] = i;
        }
    } 

function setData() {
    for ( var i = 0; i < this.numElements; ++i ) {
    this.dataStore[i] = Math.floor(Math.random() * (this.numElements + 1));
    }
} 
function clear() {
    for ( var i = 0; i < this.dataStore.length; ++i ) {
    this.dataStore[i] = 0;
        }
    } 
function insert(element) {
this.dataStore[this.pos++] = element;
} 
function toString() {
    var retstr = "";
    for ( var i = 0; i < this.dataStore.length; ++i ) {
            retstr += this.dataStore[i] + " ";
            if (i > 0 & i % 10 == 0) {
            retstr += "\n";
        }
    } 
    return retstr;
} 
function swap(arr, index1, index2) {
    var temp = arr[index1];
    arr[index1] = arr[index2];
    arr[index2] = temp;
    }


  • 测试CArray
var numElements = 100;
    var myNums = new CArray(numElements);
    myNums.setData();
    console.log(myNums.toString());

数据结构与算法javascript描述(四) 冒泡排序_第1张图片

  • js冒泡排序

function bubbleSort() {
    var numElements = this.dataStore.length;
    var temp;
            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);
          }
        }
    }
}

修改

function CArray(numElements) {
    this.dataStore = [];
    this.pos = 0;
    this.numElements = numElements;
    this.insert = insert;
    this.toString = toString;
    this.clear = clear;
    this.setData = setData;
    this.swap = swap;
    this.bubbleSort =bubbleSort; //加入bubbleSort


    for ( var i = 0; i < numElements; ++i ) {
        this.dataStore[i] = i;
        }
    } 
  • 测试:
var numElements = 10;
var mynums = new CArray(numElements);
mynums.setData();
print(mynums.toString());
mynums.bubbleSort();
print();
print(mynums.toString());
  • 运行结果

数据结构与算法javascript描述(四) 冒泡排序_第2张图片

想看详细的冒泡过程

function bubbleSort() {
    var numElements = this.dataStore.length;
    var temp;
    for (var outer = numElmeents; 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);
        }
      } 
    console.log(this.toString());
  }
}

你可能感兴趣的:(JavaScript,冒泡排序)