01.import java.util.Random; 02. 03.public class RandomSort { 04. private Random random = new Random(); 05. //数组大小 06. private static final int SIZE = 10; 07. //要重排序的数组 08. private int[] positions = new int[SIZE]; 09. 10. public RandomSort() { 11. for(int index=0; index<SIZE; index++) { 12. //初始化数组,以下标为元素值 13. positions[index] = index; 14. } 15. //顺序打印出数组的值 16. printPositions(); 17. } 18. 19. //重排序 20. public void changePosition() { 21. for(int index=SIZE-1; index>=0; index--) { 22. //从0到index处之间随机取一个值,跟index处的元素交换 23. exchange(random.nextInt(index+1), index); 24. } 25. printPositions(); 26. } 27. 28. //交换位置 29. private void exchange(int p1, int p2) { 30. int temp = positions[p1]; 31. positions[p1] = positions[p2]; 32. positions[p2] = temp; //更好位置 33. } 34. 35. //打印数组的值 36. private void printPositions() { 37. for(int index=0; index<SIZE; index++) { 38. System.out.print(positions[index]+" "); 39. } 40. System.out.println(); 41. } 42. 43. public static void main(String[] args) { 44. RandomSort rs = new RandomSort(); 45. rs.changePosition(); 46. rs.changePosition(); 47. rs.changePosition(); 48. } 49.}