bubbleSort
冒泡排序
by Chris_Walter
JavaScript
class ArrayList{
constructor(){
this.array = [];
}
insert(item){
this.array.push(item);
}
toString(){
return this.array.join();
}
// 第一個比第二個大就交換位置
swap(A, B){
[this.array[A], this.array[B]] = [this.array[B], this.array[A]];
}
bubbleSort(){
for(let i=0; i<this.array.length; i++ ){
for(let j=0; j<this.array.length-i-1; j++){
if(this.array[j] > this.array[j+1]){
this.swap(j, j + 1);
}
}
}
}
}
const nonSortedArray = (arraySize) => {
const array = new ArrayList();
for(let i=arraySize; i>0; i--){
array.insert(i);
}
console.log(`未使用冒泡排序前: ${array}`);
array.bubbleSort();
console.log(`冒泡排序後: ${array}`);
return array;
}
nonSortedArray(4);