swap 구현 방법을 설명합니다. 여기서 swap 을 이용해 1,2,3,4,5,6,7,8,9 의 형태인 배열을 뒤섞어 보겠습니다.

// ex.1)
import java.util.Arrays;
 
public class Ex01 {
 
    public static void main(String[] args) {
        int [] arg = {1,2,3,4,5,6,7,8,9};
        int result[] = new int[arg.length];
         
        // arg[] 배열을 result[] 로 복사
        result = Arrays.copyOf(arg, arg.length);
        for (int i = 0; i < (int)(result.length/2); i++) {
            swap(result, i, (int)(Math.random()*4+5));
        }
        System.out.println(Arrays.toString(result));
 
    }
     
    public static void swap(int[] temp, int a, int b) {
        int tmp = temp[a];
        temp[a] = temp[b];
        temp[b] = tmp;
    }
}


아래는 결과 화면입니다.


0 댓글