Java - 버블 정렬

정렬 알고리즘

Posted by Yan on April 1, 2021

bubble sort

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class BubbleSort {

	public static void main(String[] args) {
		int[] arr = {3,5,4,1,2};
		printArray(arr);
		bubbleSort(arr);
		printArray(arr);

	}

	private static void bubbleSort(int[] arr) {
		bubbleSort(arr, arr.length-1);
	}

	private static void bubbleSort(int[] arr, int last) {
		if (last > 0) {
			for (int i = 1; i <= last; i++) {
				if (arr[i-1] > arr[i]) {
					swap(arr, i-1, i);
				}
			}
			bubbleSort(arr, last - 1);
		}
	}

	private static void swap(int[] arr, int source, int target) {
		int tmp = arr[source];
		arr[source] = arr[target];
		arr[target] = tmp;
	}

	private static void printArray(int[] arr) {
		for (int data : arr) {
			System.out.print(data + ", ");
		}
		System.out.println();
	}
}