数据结构与算法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());

这里写图片描述

  • 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());
  • 运行结果

这里写图片描述

想看详细的冒泡过程

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());
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值