冒泡排序&乱序输出

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值