자료구조

[자료구조] 버블 정렬 (Bubble Sort)

Joo.v7 2024. 8. 22. 21:21

Bubble Sort(버블 정렬)

  • 인접한 2개의 레코드를 비교하여 크기가 순서대로 되어 있지 않으면 서로 교환하는 과정을 인덱스 처음부터 끝까지 진행한다.
  • 한 번의 정렬을 거치면 오른쪽 끝부터 정렬이 완료된다.

출처: C언어로 쉽게 풀어쓴 자료구조

 

코드

import java.util.Scanner;

// 버블 정렬
public class BubbleSort {
    public void sort(int[] array) {
        for(int i=0; i<array.length; i++) {
            for(int j=0; j<array.length-1-i; j++) {
                if(array[j] > array[j+1]) {
                    int temp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = temp;
                }
            }
        }
        for(int i=0; i<array.length; i++) {
            System.out.printf("%d ", array[i]);
        }
    }
}

// 테스트
class Test {
    public static void main(String[] args) {
        System.out.print("정렬할 수를 입력하세요 ex) 1,4,5,3 >> ");
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        String[] s = input.split(",");
        int[] array = new int[s.length];
        for(int i=0; i<s.length; i++) {
            array[i] = Integer.parseInt(s[i]);
        }
        BubbleSort bubble = new BubbleSort();
        bubble.sort(array);
    }
}

 

실행 결과

정렬할 수를 입력하세요 ex) 1,4,5,3 >> 1,8,4,6,7,2,4,3,5,10,12
1 2 3 4 4 5 6 7 8 10 12

 


 

2024.08.23 - [코딩 문제] - [코딩 문제] Anagram

 

Anagram

 

lightningtech.tistory.com

 

'자료구조' 카테고리의 다른 글

[자료구조] LinkedList  (0) 2024.09.04
[Java] ArrayList  (0) 2024.09.02
[자료구조] 스택(Stack) with Java  (0) 2024.09.02
[자료구조] 삽입 정렬 (Insertion Sort)  (0) 2024.08.27
[자료구조] 선택 정렬 (Selection Sort)  (0) 2024.08.27