목차
- 목차
- 문서에 대하여
h3. 5.4 거품정렬
인접요소를 비교하여 교환하는 모양이 마치 거품이 보글보글하는 모양이라고 해서 붙여진 이름이다.
h3. 5.4.1 거품정렬의 전략
1. i=0
2. i가 n-1이 되면 끝낸다.
3. j=i;
4. j가 n-i가 되면 7로 간다.
5. a[j-1]>a[j]이면 두 값을 교환한다.
6. j를 하나 증가시키고 4로 돌아간다.
7. i를 하나 증라시기로 2로 돌아간다.
public class BubbleSort {
public int[] bubbleSort() {
int a[] = new int[]{12,5,1,23,44,11};
int temp;
for( int i=a.length-1 ; i>1;i--)
{
System.out.println("i:"+i);
for(int j=0; j< i ; j++){
System.out.println("a["+j+"]"+a[j]);
if(a[j]> a[j+1]){
temp=a[j+1];
a[j+1] =a[j];
a[j]=temp;
}
System.out.println("bubble sort:"+ a[0]+","+ a[1]+","+ a[2]+","+ a[3]+","+ a[4]+","+ a[5]);
}
}
return a;
}
public static void main(String[] args) {
System.out.println(bubbleSort());
}
}
[결과]
i:5
a[0]12
bubble sort:5,12,1,23,44,11
a[1]12
bubble sort:5,1,12,23,44,11
a[2]12
bubble sort:5,1,12,23,44,11
a[3]23
bubble sort:5,1,12,23,44,11
a[4]44
bubble sort:5,1,12,23,11,44
i:4
a[0]5
bubble sort:1,5,12,23,11,44
a[1]5
bubble sort:1,5,12,23,11,44
a[2]12
bubble sort:1,5,12,23,11,44
a[3]23
bubble sort:1,5,12,11,23,44
i:3
a[0]1
bubble sort:1,5,12,11,23,44
a[1]5
bubble sort:1,5,12,11,23,44
a[2]12
bubble sort:1,5,11,12,23,44
i:2
a[0]1
bubble sort:1,5,11,12,23,44
a[1]5
bubble sort:1,5,11,12,23,44
문서에 대하여