java 算法--洗牌算法

方法(一)


public class Xipaisuanfa {

/**

* @param args

*/

// 數組大小

static Random random =new Random();

private int[] positions = { 1, 2, 3, 4, 5, 6, 9, 7, 8, 0 };

public Xipaisuanfa() {


}


// 重排序

public void changePosition() {

//使用for循環的目的是使得輸出的數更加無序

for (int index = positions.length - 2; index >= 0; index--) {

// 從0到index處之間隨機取一個值,跟index處的元素交換

exchange(random.nextInt(index+1), index);


}

System.out.println();

printPositions();

}


// 交換位置

private void exchange(int m, int n) {

int temp = positions[m];

positions[m] = positions[n];

positions[n] = temp;

}


// 依次打印數組的值

private void printPositions() {

for (int index = 0; index < positions.length; index++) {

System.out.print(positions[index] + " ");

}

System.out.println();

}


public static void main(String[] args) {

Xipaisuanfa rs = new Xipaisuanfa();

rs.changePosition();

rs.changePosition();

}

}


方法(二)

public class Xipaisuanfa {


/**

* @param args

*/


// 數組大小

private static int[] positions = { 1, 2, 3, 4, 5, 6, 9, 7, 8, 0 };


public static void main(String[] args) {

changePosition();

}


// 重排序

public static void changePosition() {

//使用for循環的目的是使得輸出的數更加無序

for (int index = positions.length - 1; index >= 0; index--) {

// 從0到index處之間隨機取一個值,跟index處的元素交換

int t = (int) (Math.random() * 9);

exchange(t + 1, t);

}

printPositions();

}


// 交換位置

private static void exchange(int m, int n) {

int temp = positions[m];

positions[m] = positions[n];

positions[n] = temp;

}


// 依次打印數組的值

private static void printPositions() {

for (int index = 0; index < positions.length; index++) {

System.out.print(positions[index] + " ");

}

System.out.println();

}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章