버블 정렬(bubbleSort)
function bubbleSort(arr){
for(let i = arr.length; i > 0; i--){
for(let j = 0; j < i - 1; j++){
console.log(arr,arr[i],arr[j+1]);
if(arr[j]>arr[j + 1]){
let temp = arr[j];
arr[j] = arr[j+1];
arr[j+1]= temp;
}
}
console.log("ONE PASS COMPLETE!")
}
return arr
}
bubbleSort([33,45,11,21,55,21])
function bubbleSort(arr){
for(let i = arr.length; i > 0; i--){
let noSwaps;
for(let j = 0; j < i - 1; j++){
noSwaps = true;
console.log(arr,arr[i],arr[j+1]);
if(arr[j]>arr[j + 1]){
let temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
noSwaps = false;
}
}
if(noSwaps) break;
}
return arr
}
bubbleSort([33,45,11,21,55,21])
선택 정렬 (Selection Sort)
function seletionSort(arr){
const swap = (arr,idx1,idx2)=>([arr[idx1], arr[idx2]] = [arr[idx2], arr[idx1]]);
for(let i = 0; i < arr.length; i++){
let lowest = i;
for(let j = i+1; j < arr.length; j++){
if(arr[lowest] > arr[j]){
lowest = j;
}
}
if(i !== lowest) swap(arr,i,lowest)
}
return arr;
}
seletionSort([0,34,22,10,19,17])