└ JAVA
[JAVA] 정렬 알고리즘(sorting algorithm) - 버블정렬 (Bubble Sort)
짜장이누나
2014. 7. 20. 17:17
Bubble Sort
먼저, 버블 정렬의 원리를 보도록 하자.
위와 같이'4, 2, 8, 11, 7' 5개의 원소를 버블 정렬로 정렬시키는데 한번에 4번씩 비교하고 2회전을 걸쳐 완성되었다.
총 8번의 비교를 하였다.
>> 소스보기
'4, 54, 2, 8, 63, 7, 55, 56' 8개의 원소로 버블정렬을 이용하여 정렬시키기.
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 | public class BubbleSort { public static void main(String[] args) { int[] data = { 4, 54, 2, 8, 63, 7, 55, 56 }; int temp; int cnt = 0; System.out.print("======정렬 전===============\n"); for(int m=0; m<data.length; m++) { System.out.print(data[m] + ", "); } for(int i=data.length; i>0; i--) { // for (int j=0; j<i-1; j++) { cnt++; if(data[j] > data[j+1]) { temp = data[j]; data[j] = data[j+1]; data[j+1] = temp; } } } System.out.print("\n\n======Bubble Sort=========\n"); for(int k=0; k<data.length; k++) { System.out.print(data[k] + ", "); } System.out.println("\n\n 총 회전 수 : " + cnt); } } | cs |
>> 결과보기
완성!!!!!!!!!!!!!!!!!!!