java数组算法进阶

package com.itheima;

import java.util.Random;

public class arrayoftentrain {
    public static void main(String[] args) {
        //求最值
        int[] arr1 = new int[]{33,5,22,44,55};
        int max = arr1[0];
        for (int i = 1; i < arr1.length; i++) {
            if(max < arr1[i])
                max = arr1[i];
        }
        System.out.println(max);




        //需求:生成10个1~100之间的数存入数组'
        //1.求和 2.求平均数 3.统计有多少个数据比均值小
        //一步一步来
        //先创建一个数组 , 再用循环存入十个1~100的数字
        int[] arr2 = new int[10];
        Random r = new Random();
        int sum = 0;

        int count = 0;
        for (int t = 0; t < arr2.length; t++) {
            int randnumber = r.nextInt(100) + 1;
            arr2[t] = randnumber; //存入
            //可以边存入边求和
            sum = sum + arr2[t];
        }
        System.out.println("总和为:" + sum);


        //求均值
        double avg = sum*1.0 / arr2.length;
        System.out.println("均值为:" + avg);

        //求个数
        for (int k = 0; k < arr2.length; k++) {
            if(arr2[k] < avg){
                count++;
            }
        }
        System.out.println("个数为:" + count);



        //交换数组中的数据
        int temp;
        int[] arr4 = new int[]{1,2,3,4,5};
        for (int i = 0 ,  j = arr4.length-1; i= 0){
            int randnumber = sr.nextInt(n+1);//随机索引已就绪

            swap = arrs1[m];
            arrs1[m] = arrs1[randnumber + m];
            arrs1[ randnumber + m ] = swap;

            n--;
            m++;

        }

        for (int i = 0; i < arrs1.length; i++) {
            System.out.print(arrs1[i] + " ");
        }
    
        //我写的这个是比较复杂一点的,就是当原索引+1的时候,我让随机索引取值的范围-1
        
        //当然也有简单的 ↓↓↓↓↓↓
//        int[] arrs1 = new int[]{1,2,3,4,5};
//        Random sr = new Random();
//
//        int n =arrs1.length,m = 0;
//        int swap;
//        for (int i = 0; i < arrs1.length; i++) {
//            int randomnumber = sr.nextInt(5);
//            swap = arrs1[i];
//            arrs1[i] = arrs1[randomnumber];
//            arrs1[randomnumber] = swap;
//        }
//        for (int i = 0; i < arrs1.length; i++) {
//            System.out.print(arrs1[i] + " ");
//        }
    }
}

你可能感兴趣的:(java基础算法训练,java,算法,排序算法)