bubble sort

김_리트리버·2021년 5월 15일
0

[알고리즘]

목록 보기
44/47

버블정렬

  • 인접한 요소들 끼리 자리를 계속해서 바꿔나가며 정렬
  • 자리를 바꿀 때 버블이 올라오는 것 같아서 버블정렬임
  • O(n^2)
const array = [1, 2, 3, 4, 5];

function bubbleSort(array) {
  for (let i = 0; i < array.length - 1; ++i) {
    for (let j = 0; j < array.length - 1 - i; ++j) {
      if (array[j] < array[j + 1]) {
        const temp = array[j];
        array[j] = array[j + 1];
        array[j + 1] = temp;
      }
    }
  }
}
bubbleSort(array);

profile
web-developer

0개의 댓글