java :选择排序实现 及测试用例生成方法

测试用例生成方法:

    //生成随机测试用例
    public static int [] selectSort(int n,int rodanf,int raanl){
        int []a = new int[n];
        Random random = new Random();
        if (raanl>rodanf){
            for (int i = 0; i < n; i++) {
                a[i] = (int) Math.round(Math.random()*(raanl-rodanf+1)+rodanf);
            }
        }
        return a;
    }

排序方法:

public static int[]  selectionSort(int[]a ,int n){
        for (int i = 0; i < n ; i++) {
            int minIndex = i;
            for (int j = i + 1 ; j < n ; j++) {
                if (a[j] < a[i]){
                    minIndex = j;
                    //将元素交换
                    a = swap(a, i, minIndex);
                }
            }
        }
        return a;
    }

数组元素交换方法:

//数组元素交换方法
    static int[] swap(int[]a,int i ,int j){
        try {
            if (a.length > 1 &&  i<a.length && j< a.length ){
                int temp = a[i];
                a[i] = a[j] ;
                a[j] = temp;
                return a;
            }else {
                throw new RuntimeException("请确定输入!!!");
            }
        } catch (RuntimeException e) {
            throw new RuntimeException(e);
        }
    }

主方法:

  public static void main(String[] args) {
        int[] ints = selectSort(100, 20, 100);
        System.out.println(Arrays.toString(ints));
        int[] result = selectionSort(ints, ints.length);
        System.out.println(Arrays.toString(result));
    }

运行效果:

[45, 71, 51, 84, 79, 97, 37, 59, 91, 47, 30, 26, 92, 38, 26, 47, 60, 72, 95, 82, 53, 77, 55, 100, 41, 89, 64, 57, 29, 62, 86, 56, 59, 80, 48, 37, 75, 58, 44, 80, 94, 90, 40, 28, 37, 61, 67, 71, 37, 33, 51, 90, 61, 53, 75, 28, 82, 32, 77, 65, 69, 47, 40, 62, 37, 77, 40, 54, 83, 57, 85, 90, 29, 54, 91, 51, 87, 72, 64, 48, 86, 33, 84, 94, 65, 93, 26, 78, 54, 21, 96, 21, 75, 39, 83, 69, 38, 100, 49, 81]
[21, 21, 26, 26, 26, 28, 28, 29, 29, 30, 32, 33, 33, 37, 37, 37, 37, 37, 38, 38, 39, 40, 40, 40, 41, 44, 45, 47, 47, 47, 48, 48, 49, 51, 51, 51, 53, 53, 54, 54, 54, 55, 56, 57, 57, 58, 59, 59, 60, 61, 61, 62, 62, 64, 64, 65, 65, 67, 69, 69, 71, 71, 72, 72, 75, 75, 75, 77, 77, 77, 78, 79, 80, 80, 81, 82, 82, 83, 83, 84, 84, 85, 86, 86, 87, 89, 90, 90, 90, 91, 91, 92, 93, 94, 94, 95, 96, 97, 100, 100]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值