functionCArray(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; this.selectSort = selectSort; for (let i = 0; i < numElements; ++i) { this.dataStore[i] = i; } functionsetData() { for (let i = 0; i < this.numElements; ++i) { this.dataStore[i] = Math.floor(Math.random() * (this.numElements + 1)); } } functionclear() { for (let i = 0; i < this.dataStore.length; ++i) { this.dataStore[i] = 0; } } functioninsert(element) { this.dataStore[this.pos++] = element; } functiontoString() { let str = ''; for (let i = 0; i < this.dataStore.length; ++i) { str += this.dataStore[i] + ' '; // 每逢十个换行 if (i > 0 & i % 10 == 0) { str += '\n'; } } return str; } functionswap(arr, index1, index2) { let temp = arr[index1]; arr[index1] = arr[index2]; arr[index2] = temp; } functionbubbleSort() { let numElements = this.dataStore.length; let temp; // 外循环用于遍历数组中的每一项元素 for (let outer = numElements; outer >= 2; --outer) { // 内循环用于比较元素 for (let inner = 0; inner <= outer - 1; ++inner) { if (this.dataStore[inner] > this.dataStore[inner + 1]) { swap(this.dataStore, inner, inner + 1); } } } } functionselectSort() { let min; for (let outer = 0; outer <= this.dataStore.length - 2; ++outer) { min = outer; for (let inner = outer + 1; inner <= this.dataStore.length - 1; ++inner) { if (this.dataStore[inner] < this.dataStore[min]) { swap(this.dataStore, inner, min); } } } } }
// 测试代码 let numElements = 10; let myNums = new CArray(numElements); myNums.setData(); console.log(myNums.toString()); myNums.selectSort(); console.log(myNums.toString());