.sort() 는 순서 없는 숫자를 정렬하는 함수입니다.

// ex.1)
import java.util.Arrays;
 
public class Ex01 {
 
    public static void main(String[] args)throws Exception {
         
        int number[] = {1,4,11,8,0,10,2,7,6,9};
         
        Arrays.sort(number);
         
        String num = "";
        for(int a: number) {
            num += a + ", ";
        }
        System.out.println(
                num.substring(0, num.length()-2)
        );
    }
}


아래는 결과 화면입니다.


다음은 for 문을 이용해 배열을 정렬해 보겠습니다.

// ex.2)
public class Ex01 {
 
    public static void main(String[] args)throws Exception {
         
        int number[] = {1,4,11,8,0,10,2,7,6,9};
         
        int tmp;
         
        for (int i = 0; i < number.length; i++) {
            for(int j = 0; j < i; j++) {
                if(number[j] > number[i]) {
                    tmp = number[i];
                    number[i] = number[j];
                    number[j] = max;
                }
            }
        }
        for (int i = 0; i < number.length; i++) {
            System.out.print(number[i] + ", ");
        }
        // 결과: 0, 1, 2, 4, 6, 7, 8, 9, 10, 11 
    }
}


다음은 역순으로 정렬해 보겠습니다.

// ex.3)
public class Ex01 {
 
    public static void main(String[] args)throws Exception {
         
        int number[] = {1,4,11,8,0,10,2,7,6,9};
         
        int tmp;
         
        for (int i = 0; i < number.length; i++) {
            for(int j = 0; j < i; j++) {
                if(number[j] < number[i]) {
                    tmp = number[i];
                    number[i] = number[j];
                    number[j] = max;
                }
            }
        }
        for (int i = 0; i < number.length; i++) {
            System.out.print(number[i] + ", ");
        }
        // 결과: 11, 10, 9, 8, 7, 6, 4, 2, 1, 0
    }
}


0 댓글