zoukankan      html  css  js  c++  java
  • 冒泡排序以及随机乱序

    编写程序,对数组进行排序,使用冒泡法排序,并增加随机性,使得数组乱序输出。

    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);该代码避免了随机出相同的数组下标,从而实现整个数组无重复的乱序输出。

  • 相关阅读:
    浮点数小数点后开始非零数字的起始位置
    关于接口测试
    性能测试模型之曲线拐点模型
    2018春招实习笔试面试总结(PHP)
    mysql删除表中的记录
    浅析单点登录
    MySQL两种引擎的比较
    Redis初探(windows/linux安装)
    剑指offer试题(PHP篇三)
    剑指offer试题(PHP篇二)
  • 原文地址:https://www.cnblogs.com/Andya/p/5687401.html
Copyright © 2011-2022 走看看