본문 바로가기
스마트인재개발원/자바

[JAVA] swap 버블정렬(bubble sort)/generic을 사용한 버블정렬

by 죠졍니 2022. 7. 30.
728x90
반응형
SMALL

버블 정렬이란

  • 1번째 자료< - > 2번째자료 , 2번째 자료 < - > 3번째 자료, 3번째 자료 < - > 4번째 자료 ●●● 이런식으로 마지막까지 돌아서 가장 큰 숫자가 제일 마지막에 도달하면 1회전
  • 위 과정을 계속 반복

 

 

 


일반적 버블정렬(bubble sort)

  • swap을 사용하여 작성한 자바 소스코드
public class bubbleSort{

     public static int swap(int a, int b){
        return a;
    }   

    public static void bubble_sort(int[]a){
        for(int i=0;i<a.length-1;i++){
            for(int j=0;j<a.length-i-1;j++){
                if(a[j]>a[j+1])
                {
                    a[j+1]=swap(a[j],a[j]=a[j+1]);
                }
            }
        }
    }
    public static void main(String[] args){
        int a[] = { 23, 7, 19, 78, 3};
        for(int data:a){
            System.out.print(data+ "  ");
        }
        System.out.print("\n");
        bubble_sort(a);
        for(int data:a){
            System.out.print(data+ "  ");
        }
    }
}

 

 

 

 


결과값

 

 

 

 


제네릭을 이용한 버블정렬(bubble sort)

  • 제네릭 이용한 버블정렬 자바 소스코드
import java.util.Arrays;

public class genericbubbleSort {
    public <T extends Comparable<T>> void bubbleSort(T[] a) {
        for(int i = a.length - 1; i > 0; i--) {
            for(int j = 0 ; j < i ; j++) {
                if (a[j].compareTo(a[j + 1]) > 0 ) {
                    T item = a[j];
                   a[j] = a[j + 1];
                   a[j + 1] = item;
                }
            }
        }
    }
    public void sort() {
        Integer[] List =  {23, 7, 19, 78, 3};

        System.out.println(Arrays.toString(List));
        bubbleSort(List);
        System.out.println( Arrays.toString(List));

    }
    public static void main(String[] args) {
        genericbubbleSort bubble = new genericbubbleSort();
        bubble.sort();
    }
}

결과값

 

 

728x90
반응형
LIST