버블 정렬 - Node.js

프동프동·2022년 8월 2일
0

알고리즘 - Node.js

목록 보기
77/116
post-thumbnail

버블 정렬


문제

N개이 숫자가 입력되면 오름차순으로 정렬하여 출력하는 프로그램을 작성하세요. 정렬하는 방법은 버블정렬입니다.

입력

첫 번째 줄에 자연수 N(1<=N<=100)이 주어집니다.
두 번째 줄에 N개의 자연수가 공백을 사이에 두고 입력됩니다. 각 자연수는 정수형 범위 안에 있습니다.

출력

오름차순으로 정렬된 수열을 출력합니다.

입력 예시 1

6
13 5 11 7 23 15

출력 예시 1

5 7 11 13 15 23


해결방법

function solution(sample_data) {
  let answer = sample_data;
  for (let i = 0; i < sample_data.length - 1; i++) {
    for (let j = 0; j < sample_data.length - i - 1; j++) {
      if (sample_data[j] > sample_data[j + 1]) {
        [sample_data[j], sample_data[j + 1]] = [
          sample_data[j + 1],
          sample_data[j],
        ];
      }
    }
  }

  return answer;
}
let sample_data = [13, 5, 11, 7, 23, 15];

console.log(solution(sample_data));

profile
좋은 개발자가 되고싶은

0개의 댓글