본문 바로가기

JAVA/알고리즘 예제

[JAVA] 버블 정렬(Bubble Sort)

예제배열 {7,9,4,3,1}

1~4회전 결과가 이렇게 출력되도록 하시오


기본적인 버블정렬

package jungbo;


public class T22BubbleSort {

public static void main(String[] args) {

int array[] = {7,9,4,3,1};

int row, col;

int cup;

for(row=0;row<=3;row++){

for(col=0;col<=3-row;col++){

if(array[col]>array[col+1]){

cup = array[col];

array[col]=array[col+1];

array[col+1]=cup;

}

}

for(col=0;col<=4;col++){

System.out.printf("%2d", array[col]);

}

System.out.println();

}

}

}


위의 예제배열은 4회전이 되기 때문에 

예제 배열을 {3,4,5,7,6}으로 바꿔서 1회전만에 정렬이 끝나도록한다.

정렬이 끝나도 4회전하는 위 로직과는 다르게 

정렬이 끝나면 더이상 반복문을 돌리지 않고 탈출하도록

성능을 개선한다.


실행결과가


3 4 5 6 7


이 되도록 하시오(1회전만에 종료)


향상된 버블정렬

package jungbo;


public class T22BubbleSort {

public static void main(String[] args) {

int array[] = {3,4,5,7,6};

int row, col;

int cup;

int sw;

for(row=0;row<=3;row++){

sw=0;

for(col=0;col<=3-row;col++){

if(array[col]>array[col+1]){

cup = array[col];

array[col]=array[col+1];

array[col+1]=cup;

sw=1;

}

}

if(sw==0)break;

for(col=0;col<=4;col++){

System.out.printf("%2d", array[col]);

}

System.out.println();

}

}

}




<A[5]>                    <A[M]>


sw=0


[row = 1, 4, 1]             [row=1, M, 1]


[col = 1, 5-row, 1]          [col = 1, M-row, 1]


A(col) > A(col+1)

yes      교환

no 아무것도안함


교환이 있었다면 sw=1


sw=1이라면 반복문을 탈출하고 더이상 정렬하지마라


'JAVA > 알고리즘 예제' 카테고리의 다른 글

[JAVA] 순위(석차) 계산기  (1) 2016.09.01
[JAVA] ㄹ자 출력  (1) 2016.08.31
[JAVA] 선택 정렬(Selection Sort)  (1) 2016.08.31
[JAVA] 마방진  (1) 2016.08.31
[JAVA] 모래시계 찍기  (1) 2016.08.30