JAVA/알고리즘

버블정렬

lovineff 2020. 6. 4. 17:37
public class BubbleSort {
    //    버블정렬
    static int[] bubbleSortAsc(int[] x){
        int temp = 0;
        for(int i=0 ; i < x.length ; i++){
            for(int j=x.length - 1 ; j > i ; j--){
                if(x[j] < x[j-1]){  // 우측 값이 더 큰경우 swap
                    temp = x[j-1];  // 큰 수를 넣는다
                    x[j-1] = x[j];
                    x[j] = temp;
                }
            }
        }
        return x;
    }

    //    버블정렬 DESC 처리
    static int[] bubbleSortDesc(int[] x){
        int temp = 0;
        for(int i=0 ; i < x.length ; i++){
            for(int j=x.length - 1 ; j > i ; j--){
                if(x[j] > x[j-1]){  // 우측 값이 더 큰경우 swap
                    temp = x[j-1];  // 큰 수를 넣는다
                    x[j-1] = x[j];
                    x[j] = temp;
                }
            }
        }
        return x;
    }

    //    처음부터 정렬하는 버블정렬
    static int[] bubbleSortAscStart0(int[] x){
        int temp = 0;
        for(int i = x.length ; i > 0 ; i--){
            for(int j = 0 ; j < i - 1 ; j++){
                if(x[j] < x[j+1]){  // 우측 값이 더 큰경우 swap
                    temp = x[j+1];  // 큰 수를 넣는다
                    x[j+1] = x[j];
                    x[j] = temp;
                }
            }
        }
        return x;
    }

    // 버블정렬 프로세스를 보여준다.
    static int[] showBubbleSortProcess(int[] x){
        int temp = 0;
        int changeCnt = 0;  // swap 수
        int compareCnt = 0; // 비교수
        boolean isChange = false;   // 값 swap 여부

        for(int i=0 ; i < x.length ; i++){
            if(i < x.length -1)
                System.out.println("패스 " + (i+1) + " :");

            for(int j=x.length - 1 ; j > i ; j--){
                compareCnt++;

                if(x[j] < x[j-1]){  // 우측 값이 더 큰경우 swap
                    isChange = true;
                    changeCnt++;
                }else{
                    isChange = false;
                }

                System.out.println(makeSortProcess(x, j, isChange));

                if(isChange){       // swap
                    temp = x[j-1];
                    x[j-1] = x[j];
                    x[j] = temp;
                }
            }
        }

        System.out.println("비교를 " + compareCnt + "회 했습니다.");
        System.out.println("교환은 " + changeCnt + "회 했습니다.");
        return x;
    }

    public static StringBuilder makeSortProcess(int[] x, int compareLocation, boolean isChange){
        StringBuilder sb = new StringBuilder();

        sb.append("\t");
        for(int i=0 ; i < x.length ; i++){
            if(i == compareLocation - 1){
                sb.append(x[i]).append(isChange ? " + " : " - ");
            }else{
                sb.append(x[i]).append(" ");
            }
        }

        return sb;
    }

    public static void main(String[] args) {
        int[] x = new int[]{6,4,3,7,1,9,8,};

        System.out.println("오름차순 정렬");
        showBubbleSortProcess(x);
    }
}