冒泡排序以及随机乱序

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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");          
        }
    }
}

  运行结果:

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

posted @   Andya_net  阅读(561)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示