본문 바로가기

재미있는 알고리즘/알고리즘 소스 코드

버블정렬(Bubble Sort) - 오름차순 정렬

반응형

버블정렬(Bubble Sort)의 비교적 쉬운 알고리즘으로 기본 개념은 이웃한 데이터들을 서로 비교하여 차례로 정렬합니다. 


[자바 소스코드]


  1. public
     class BubbleSort {
  2.  
  3.     public static void main(String[] args) {
  4.         int data[] = { 7445259012652440980 }// 원본값을 배열로 설정
  5.        
  6.         System.out.print("정렬 이전 원 데이타 : ");
  7.         printArray original_data = new printArray(data);
  8.         System.out.println("----------------------------------------------------");
  9.  
  10.        
  11.         Bubble_Sort i = new Bubble_Sort(data);
  12.        
  13.         System.out.println("-----------------------------------------------------");
  14.         System.out.print("선택 정렬 후 데이타 : ");
  15.         printArray sorted_data = new printArray(data);
  16.     }
  17. }
  18.  
  19. class printArray {
  20.    
  21.     public printArray(int arrayData[]){
  22.         for(int i=0; i<arrayData.length; i++){
  23.             System.out.print(arrayData[i] + " ");
  24.         }
  25.         System.out.println();
  26.      }
  27. }
  28.  
  29. class Bubble_Sort {
  30.    
  31.     public Bubble_Sort (int[] arrayData) {
  32.  
  33.         int temp;
  34.  
  35.         for (int i=arrayData.length-1; i>0; i--) {
  36.             System.out.print(i + "번째 선택 정렬 중 데이타 : ");
  37.             printArray sorting_data = new printArray(arrayData);
  38.  
  39.             for (int j=0; j<i; j++) {
  40.                 if(arrayData[j] > arrayData[j+1] ) {
  41.                     temp = arrayData[j];
  42.                     arrayData[j] = arrayData[j+1];
  43.                     arrayData[j+1] = temp;
  44.                 }
  45.             }
  46.            
  47.         }
  48.     }
  49. }
  50.  

[실행 결과]

  1. 정렬 이전 원 데이타 : 74 45 25 90 12 65 24 40 9 80
  2. ----------------------------------------------------
  3. 9번째 선택 정렬 중 데이타 : 74 45 25 90 12 65 24 40 9 80
  4. 8번째 선택 정렬 중 데이타 : 45 25 74 12 65 24 40 9 80 90
  5. 7번째 선택 정렬 중 데이타 : 25 45 12 65 24 40 9 74 80 90
  6. 6번째 선택 정렬 중 데이타 : 25 12 45 24 40 9 65 74 80 90
  7. 5번째 선택 정렬 중 데이타 : 12 25 24 40 9 45 65 74 80 90
  8. 4번째 선택 정렬 중 데이타 : 12 24 25 9 40 45 65 74 80 90
  9. 3번째 선택 정렬 중 데이타 : 12 24 9 25 40 45 65 74 80 90
  10. 2번째 선택 정렬 중 데이타 : 12 9 24 25 40 45 65 74 80 90
  11. 1번째 선택 정렬 중 데이타 : 9 12 24 25 40 45 65 74 80 90
  12. -----------------------------------------------------
  13. 선택 정렬 후 데이타 : 9 12 24 25 40 45 65 74 80 90


반응형