算法:顺序遍历,每次生成一个随机位置,和当前位置的元素互换。
运行时间是线性的,测试程序如下:
import java.util.Random;
public class Test{
public static void main(String args[]) {
int[] arr = new int[10];
arr = getSequence(10);
for(int i=0; i<10; i++){
System.out.println(arr[i]);
}
}
private static int[] getSequence(int no) {
int[] sequence = new int[no];
for(int i = 0; i < no; i++){
sequence[i] = i;
}
Random random = new Random();
for(int i = 0; i < no; i++){
int p = random.nextInt(no);
int tmp = sequence[i];
sequence[i] = sequence[p];
sequence[p] = tmp;
}
random = null;
return sequence;
}
}
每次输出都是一个 0~9 的非重复随机排列序列。
链接:www.cnblogs.com/noam/archive/2011/03/14/1983974.html