selectionSort

選擇排序

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]];
	}
	selectionSort(){
	  let length = this.array.length;
	  for(let i=0; i<length - 1; i++){
		  let minIndex = i;
			for(let j=i; j<length; j++){
				console.log(minIndex, j);
			  if(this.array[minIndex] > this.array[j]){
				  minIndex = j;
				}
			}
			if(i !== minIndex){
			  console.log(`swap: ${i}, ${minIndex}`);
			  this.swap(i, minIndex);
			}
		}
	}
}

const nonSortedArray = (arraySize) => {
  const array = new ArrayList();
	for(let i=arraySize; i>0; i--){
	  array.insert(i);
	}
	console.log(`未使用選擇排序前: ${array}`);
	array.selectionSort();
	console.log(`選擇排序後: ${array}`);
	return array;
}

nonSortedArray(4);