冒泡排序以及随机乱序
2016-07-20 10:36
267 查看
编写程序,对数组进行排序,使用冒泡法排序,并增加随机性,使得数组乱序输出。
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] + "\t"); } 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("\nAfter sorting, the order of elements of array_a is : "); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + "\t"); } System.out.println("\nAfter 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 + "\t"); } } }
运行结果:
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);该代码避免了随机出相同的数组下标,从而实现整个数组无重复的乱序输出。
相关文章推荐
- thinkphp默认的URL如何访问
- C++中的trivial解释
- PHP写文件函数
- Android系统启动过程【转】
- Matlab获取矩阵的大小
- IOS 开发中的CALayer与UIView
- opencv将图片组合成视频播放
- free结果输出中的-/+ buffers/cache是什么意思
- matlab1
- UVALive 6937 The Imp
- 从外籍人才使用上看甲午海战:中国输在“洋教头”手下
- 校园到职场,正益移动助力90后就业创业
- struts2基础篇(1)
- thinkphp实现文件下载函数
- Spatial Transformer Layer 实验结果 及 分析
- 性能测试总结(二)---测试流程篇
- Android性能优化之常见的内存泄漏
- mong 备份和恢复
- 自定义控件其实很简单1/2
- 内存泄漏之内部类handler()