Language/JAVA
[JAVA] 버블정렬 (Bubble Sort) 동작과정/ 예제
영보로그
2023. 10. 18. 11:05
반응형
버블정렬 (Bubble Sort)
- 서로 인접한 두 원소를 검사하여 크기가 큰 순서대로 되어 있지 않으면 서로 교환
- 구현이 매우 간단
package threeDay;
// 버블 정렬
public class ExampleTwo {
public static void main ( String [] args) {
int [] dataList = {9,1,8,2,7,3,6,4,5};
int count = 0; // 반복 횟수
while(true) {
count ++;
boolean sw = false ;
for ( int i = 0; i < dataList.length -1; i++ ) {
if(dataList[i] > dataList[i + 1]) {
int temp = dataList[i];
dataList[i] = dataList[i + 1];
dataList[i + 1] = temp;
sw = true ;
}
}
if (!sw) { //스위칭
break;
}
}
for(int j = 0; j < dataList.length;j ++) {
System.out.print(dataList[j] + ", ");
}
System.out.println();
System.out.println("반복 횟수는 " + count + "번 입니다. ");
}
}
반응형