본문 바로가기
Algorithm

[Algorithm] Bubble Sort

by NJ94 2023. 9. 7.

알고리즘에대한 자신감이 없어, 

시간이 엄청 걸려도 그림만 보고 

JS 코드로 코딩해보려고한다.

 

아래의 그림은, 아래에 첨부되어있는 링크에서 가져온 이미지 이고,

정리가 너무 잘되어있어서 좋았다.

 

https://gmlwjd9405.github.io/2018/05/06/algorithm-bubble-sort.html

 

 

 

그림만 보고 아래의 코드를 제작해봤는데

나름 그 전에 알고리즘 공부를 했던 것이 도움이 되었나보다.

 

// 7 4 5 1 3 - 오름차순, 버블정렬

let arr = [7, 4, 5, 1, 3];
let len = arr.length;

for(let i=0; i<len; i++) {
    for(let j= i + 1; j<len; j++) {
        if(arr[i] > arr[j]) {
            let temp = arr[j];
            arr[j] = arr[i];
            arr[i] = temp;
        }
    }
}

console.log(arr);
// 1, 3, 4, 5, 7

 

이제 내림차순도 해봐야겠다.

 

// 7, 4, 5, 1, 3 내림차순, 버블정렬

let arr = [7, 4, 5, 1, 3];
let len = arr.length;

for(let i=0; i<len; i++) {
    for(let j=i + 1; j<len; j++) {
        if(arr[i] < arr[j]) {
            let temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }
}

console.log(arr);
// [7, 5, 4, 3, 1]

 

나름 잘했네 

버블 정렬에 대한 상세 내용 정리를 해봐야겠다.

 

😶 버블정렬

- 상당히 느리지만, 코드가 단순하기 때문에 자주 사용된다. 원소의 이동이 거품이 수면으로 올라오는 듯한 모습을 보이기 때문에 지어진 이름

 

https://gmlwjd9405.github.io/2018/05/06/algorithm-bubble-sort.html

 

 

https://gmlwjd9405.github.io/2018/05/06/algorithm-bubble-sort.html

 

[알고리즘] 버블 정렬(bubble sort)이란 - Heee's Development Blog

Step by step goes a long way.

gmlwjd9405.github.io

'Algorithm' 카테고리의 다른 글

[Algorithm] Algorithm  (1) 2023.12.15
[Algorithm] QuickSort  (0) 2023.09.09