JavaScript의 버블 정렬
Harshit Jindal
2023년10월12일
JavaScript
JavaScript Algorithm

이 자습서에서는 JavaScript에서 버블 정렬을 사용하여 배열을 정렬하는 방법을 설명합니다.
버블 정렬은 간단한 정렬 알고리즘입니다. 인접한 요소를 반복적으로 비교하고 순서가 잘못된 경우 교체하여 작동합니다. 반복되는 비교는 배열의 끝 부분에서 가장 작은/가장 큰 요소를 버블 링하므로이 알고리즘을 버블 정렬이라고합니다. 비효율적이지만 여전히 정렬 알고리즘의 기초를 나타냅니다.
JavaScript 버블 정렬 구현
function bubbleSort(items) {
var length = items.length;
for (var i = 0; i < length; i++) {
for (var j = 0; j < (length - i - 1); j++) {
if (items[j] > items[j + 1]) {
var tmp = items[j];
items[j] = items[j + 1];
items[j + 1] = tmp;
}
}
}
}
var arr = [5, 4, 3, 2, 1];
bubbleSort(arr);
console.log(arr);
출력:
[1, 2, 3, 4, 5]
튜토리얼이 마음에 드시나요? DelftStack을 구독하세요 YouTube에서 저희가 더 많은 고품질 비디오 가이드를 제작할 수 있도록 지원해주세요. 구독하다
작가: Harshit Jindal
Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.
LinkedIn