문제
- start looping from the end of the array towards the beginning with a variable called 'i'
- start an inner loop with a variable called 'j' from the beginning until i-1
- if arr[j] is greater than arr[j+1], swap those two values
- return the sorted array
예시
[12,4,5,2,23]
풀이
function bubbleSort(arr) {
const swap = (arr, idx1, idx2) => {
[arr[idx1], arr[idx2]] = [arr[idx2], arr[idx1]];
}
for (let i = arr.length; i > 0; i--) {
for(let j = 0; j < i-1; j++) {
if(arr[j] > arr[j+1] {
swap(arr, j, j+1);
}
}
}
return arr;
}
bubbleSort([12, 4, 5, 2, 23]
한 줄 평
- i를 arr.length까지로 limit을 정하고 하나씩 범위를 줄이는 방법
- 배열 내에서 가장 큰 숫자는 for문을 처음으로 돌 때 맨 끝으로 정렬되게 되어있으므로 for문을 두번째로 돌 때 다시 체크할 필요가 없음