编写程序,对数组进行排序,使用冒泡法排序,并增加随机性,使得数组乱序输出。
package com.liaojianya.chapter1; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * This program demonstrates the sort and out-of-order of array. * * @author LIAO JIANYA 2016年7月20日 */ public class OrderAndOutOfOrder { public static void main(String[] args) { int[] a = { 25, 24, 12, 76, 98, 101, 90, 28 }; System.out.println("Before sorting, the order of elements of array_a is : "); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } for (int i = 0; i < a.length; i++) { for (int j = i; j < a.length - 1; j++) { if (a[i] > a[j + 1]) { int temp = a[i]; a[i] = a[j + 1]; a[j + 1] = temp; } } } System.out.println(" After sorting, the order of elements of array_a is : "); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } System.out.println(" After random, the out-of-order of elements of array_a is : "); int out = 0; int outIndex = 0; Random ran = new Random(); List<Integer> list = new ArrayList<Integer>(); for(int i : a) { list.add(i); } for(int i = 0; i < a.length; i++) { outIndex = ran.nextInt(list.size()); out = (int) list.get(outIndex); list.remove(outIndex); System.out.print(out + " "); } } }
运行结果:
Before sorting, the order of elements of array_a is : 25 24 12 76 98 101 90 28 After sorting, the order of elements of array_a is : 12 24 25 28 76 90 98 101 After random, the out-of-order of elements of array_a is : 25 28 76 98 12 24 101 90
分析:利用List类进行乱序输出,其中比较重要的是list.remove(outIndex);该代码避免了随机出相同的数组下标,从而实现整个数组无重复的乱序输出。