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();

}

}


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