bubble-sort

#algorithm

  • ์™œ ์ด๋Ÿฐ ์ด๋ฆ„?

    • ์ •๋ ฌ ์ค‘์—, ๋ฐฐ์—ด์—์„œ ๊ฐ€์žฅ ํฐ ์š”์†Œ๊ฐ€ ๋งจ ๋’ค๋กœ ์ด๋™ (Bubble up) ๋˜๊ธฐ ๋•Œ๋ฌธ์—

  • ์‹œ๊ฐ„ ๋ณต์žก๋„

    • O(N^2)

์˜ˆ์ œ ์ฝ”๋“œ

public class BubbleSort {

    public static void main(String[] args) {
        int[] arr = {2, 1, 4, 0, 3};
        sort(arr);
        System.out.println(arr);
    }

    public static int[] sort(int[] arr) {
        int length = arr.length;

        for (int i = 0; i < length - 1; i++) {
            for (int j = 0; j < length - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    swap(arr, j, j + 1);
                }
            }
        }
        return arr;
    }

    public static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}

์ฐธ๊ณ 

  • https://st-lab.tistory.com/195

Last updated