首页 > 代码库 > Javascript经典算法学习1:产生随机数组的辅助类

Javascript经典算法学习1:产生随机数组的辅助类

辅助类

在几个经典排序算法学习部分,为方便统一测试不同算法,新建了一个辅助类,主要功能为:产生指定长度的随机数组,提供打印输出数组,交换两个元素等功能,代码如下:

function ArraySortUtility(numOfElements) {    this.dataArr = [];    this.pos = 0;    this.numOfElements = numOfElements;    this.insert = insert;    this.toString = toString;    this.clear = clear;    this.setData =http://www.mamicode.com/ setData;    this.swap = swap;    for (var i = 0; i < numOfElements.length; i++) {        this.dataArr[i] = i;    }}ArraySortUtility.prototype={    constructor:ArraySortUtility,    bubbleSort: bubbleSort,    //下面添加新的方法}

几个重要方法的实现如下:

function setData() {    for (var i = 0; i < this.numOfElements; i++) {        this.dataArr[i] = Math.floor(Math.random() * (this.numOfElements + 1));    }}

其它几个函数实现如下:

function clear() {    for (var i = 0; i < this.dataArr.length; i++) {        this.dataArr[i] = 0;    }}function insert(element) {    this.dataArr[this.pos++] = element;}function toString() {    var restr = "";    for (var i = 0; i < this.dataArr.length; i++) {        restr += this.dataArr[i] + " ";        if (i > 0 & i % 10 == 0) {            restr += "\n";        }    }    return restr;}function swap(arr, index1, index2) {    var temp = arr[index1];    arr[index1] = arr[index2];    arr[index2] = temp;}

 

Javascript经典算法学习1:产生随机数组的辅助类