Algorithm

bubble sort

이상욱1 2015. 4. 15. 13:43

결과값은 정렬되는데  count가 다도는데 마치 아래는 다 안도는거 같아서 뭔가 찝찝하다 

나중에 다시 알아보자 




/*1. 인접한 두 인덱스를 비교해서 정렬이 되어있지 않을경우 정렬한다.


2. 리스트 처음부터 끝까지 이런식의 정렬을 하고 나면 제일 마지막 리스트에는 제일 큰 값(또는 작은 값)이 저장된다.


3. 다시 처음 리스트부터 마지막 리스트 이전 리스트까지 서로 이웃한 인덱스를 비교해가며 정렬한다.


4. 위 방법으로 계속해서 정렬한다.*/




public class Bubblesort {


public static void main(String[] args) {

int arr[]={4, 3, 12 , 5 , 2 , 1 , 8 ,9};

int count=0;

for(int i=0;i<7;i++ ){

for(int j=0; j<7 ; j++){

count++;

if(arr[j] >arr[j+1]){

int tmp =0;

tmp=arr[j];

arr[j]=arr[j+1];

arr[j+1]=tmp;

}

}

}


for(int i=0;i<8;i++ ){

System.out.println("arr[i]="+arr[i ]);


}

System.out.println(count);

}

}











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
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);
    }
}



>> 결과보기



완성!!!!!!!!!!!!!!!!!!!