```java
import java.util.Arrays;
public class BubbleSort {
public static void bubbleSort(int[] arr) {
int count = 0;
System.out.println("Before BubbleSort");
Arrays.stream(arr).forEach(value -> System.out.print(value + " "));
System.out.println();
for (int i = 0; i < arr.length-1; i++) {
for (int j = 0; j < arr.length-i-1; j++) {
count++;
if (arr[j] > arr[j+1]) {
swap(arr, j, j+1);
}
}
}
System.out.println("After BubbleSort Result");
System.out.println("The number of count : " + count);
Arrays.stream(arr).forEach(value -> System.out.print(value + " "));
System.out.println();
}
public static void ImprovedBubbleSort(int[] arr){
System.out.println("Before ImprovedBubbleSort");
Arrays.stream(arr).forEach(value -> System.out.print(value + " "));
System.out.println();
int swapped = 1;
int count = 0;
for (int i = 0; i < arr.length-1; i++) {
// 교환할 필요가 없다면 loop를 빠져나온다.
// 회전 loop 단계에서 swap = 0이면 break
if(swapped==0 ){
break;
}
swapped = 0;
for (int j = 0; j < arr.length-i-1; j++) {
count++;
if (arr[j] > arr[j+1]) {
swap(arr, j, j+1);
swapped = 1;
}
}
}
System.out.println("After ImprovedBubbleSort Result" );
System.out.println("The number of count : " + count);
Arrays.stream(arr).forEach(value -> System.out.print(value + " "));
System.out.println();
}
public static void main(String[] args) {
int[] arr1 = new int[]{10,9,8,7,6,5,4,3,2,1};
int[] arr2 = new int[]{10,9,8,7,6,5,4,3,2,1};
int[] arr3 = new int[]{1,2,3,4,5,6,7,8,9,10};
int[] arr4 = new int[]{1,2,3,4,5,6,7,8,9,10};
bubbleSort(arr1);
System.out.println();
ImprovedBubbleSort(arr2);
System.out.println();
bubbleSort(arr3);
System.out.println();
ImprovedBubbleSort(arr4);
}
}
```java
Before BubbleSort
10 9 8 7 6 5 4 3 2 1
After BubbleSort Result
The number of count : 45
1 2 3 4 5 6 7 8 9 10
Before ImprovedBubbleSort
10 9 8 7 6 5 4 3 2 1
After ImprovedBubbleSort Result
The number of count : 45
1 2 3 4 5 6 7 8 9 10
Before BubbleSort
1 2 3 4 5 6 7 8 9 10
After BubbleSort Result
The number of count : 45
1 2 3 4 5 6 7 8 9 10
Before ImprovedBubbleSort
1 2 3 4 5 6 7 8 9 10
After ImprovedBubbleSort Result
The number of count : 9
1 2 3 4 5 6 7 8 9 10
성능
최악의 경우 복잡도 :O(n2)
최선의 경우 복잡도: O(n)
평균 복잡도 : O(n2)
최악의 경우 공간 복잡도: O(1) 보조공간