본문 바로가기
Tech/알고리즘

버블정렬 (BubbleSort)

by Dog발자. 2020. 6. 1.
반응형

- 버블정렬(BubbleSort)

  • 가장 기본인 정렬 방법 중 하나이다.
  • 인접한 값을 비교하여 정렬하는 방법이다.
  • 2중 for 문을 사용하기 때문에 시간 복잡도는 O(n^2)이며 그렇기 때문에 계산하는 시간이 느리다.
public class BubbleSort {
	public static void bubbleSort(int[] arr) {
	    int temp = 0;
		for(int i = 0; i < arr.length; i++) {
			for(int j= 1 ; j < arr.length-i; j++) {
				if(arr[j]<arr[j-1]) { // 부호를 바꾸면 내림 차순이 된다.
					temp = arr[j-1];
					arr[j-1] = arr[j];
					arr[j] = temp;
				}
				System.out.println(Arrays.toString(arr));
			}
		}
		System.out.println("결과 : " + Arrays.toString(arr));
	}
	
	public static void main(String[] args) {
		int[] list = {1 , 2, 4, 8, 10, 7, 3, 9, 5, 6};
		bubbleSort(list);
	}
}

결과

[1, 2, 4, 8, 10, 7, 3, 9, 5, 6]
[1, 2, 4, 8, 10, 7, 3, 9, 5, 6]
[1, 2, 4, 8, 10, 7, 3, 9, 5, 6]
[1, 2, 4, 8, 10, 7, 3, 9, 5, 6]
[1, 2, 4, 8, 7, 10, 3, 9, 5, 6] // 7 - 10 위치 교환
[1, 2, 4, 8, 7, 3, 10, 9, 5, 6] // 3 - 10 위치 교환
[1, 2, 4, 8, 7, 3, 9, 10, 5, 6] // 9 - 10 위치 교환
[1, 2, 4, 8, 7, 3, 9, 5, 10, 6]
[1, 2, 4, 8, 7, 3, 9, 5, 6, 10]
[1, 2, 4, 8, 7, 3, 9, 5, 6, 10]
[1, 2, 4, 8, 7, 3, 9, 5, 6, 10]
[1, 2, 4, 8, 7, 3, 9, 5, 6, 10]
[1, 2, 4, 7, 8, 3, 9, 5, 6, 10]
[1, 2, 4, 7, 3, 8, 9, 5, 6, 10]
[1, 2, 4, 7, 3, 8, 9, 5, 6, 10]
[1, 2, 4, 7, 3, 8, 5, 9, 6, 10]
[1, 2, 4, 7, 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