function CArray(numElements) { this.dataStore = []; this.numElements = numElements; this.prints = prints; this.setData = setData; this.bubbleSort = bubbleSort; this.insertionSort = insertionSort; 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; } function insertionSort() { var temp, inner; for ( var outer = 1; outer < this.dataStore.length; ++outer) { temp = this.dataStore[outer]; //选中一个值作为临时值,使得其前面的数依次与它进行比较 inner = outer; while (inner > 0 && (this.dataStore[inner - 1] >= temp)) { this.dataStore[inner] = this.dataStore[inner - 1]; --inner; } this.dataStore[inner] = temp; } } 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);//交换两数的位置 //从左到右依次两两比较 } } } } function selectionSort() { var min; for ( var outer = 0; outer < this.dataStore.length - 1; ++outer) { min = outer; for ( var inner = outer + 1; inner < this.dataStore.length; ++inner) { if (this.dataStore[inner] < this.dataStore[min]) { min = inner; } } swap(this.dataStore, outer, min); } } var numElements = 10000; var myNums = new CArray(numElements); myNums.setData(); //myNums.prints(); var start = new Date().getTime(); myNums.bubbleSort(); var stop = new Date().getTime(); var elapsed = stop - start; document.write(" 对 " + numElements + " 个元素执行冒泡排序消耗的时间为: " + elapsed + " 毫秒。 " + "<br />"); start = new Date().getTime(); myNums.selectionSort(); stop = new Date().getTime(); elapsed = stop - start; document.write(" 对 " + numElements + " 个元素执行选择排序消耗的时间为: " + elapsed + " 毫秒。 " + "<br />"); start = new Date().getTime(); myNums.insertionSort(); stop = new Date().getTime(); elapsed = stop - start; document.write(" 对 " + numElements + " 个元素执行插入排序消耗的时间为: " + elapsed + " 毫秒。 " + "<br />");