插入排序过程数据演示:
function CArray(numElements) {
this.dataStore = [];
this.numElements = numElements;
this.prints = prints;
this.setData = setData;
//this.bubbleSort = bubbleSort;
this.insertionSort = insertionSort;
}
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 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;
}
}
var numElements = 100;
var myNums = new CArray(numElements);
myNums.setData();
myNums.insertionSort();
myNums.prints();