詩あ遠方

Menu

给出一组年龄,用冒泡排序求最大年龄,最小年龄

法一

//求出最大年龄,求出最小年龄,求出平均年龄
        int[] ages = {34,11,45,23,16};
        boolean flag = true ;
        for (int i = 4; flag && i >0 ; i--) {
            flag = false ;
            for (int j = 0; j < i; j++) {
                if(ages[j]>ages[j+1]){
                    int temp = ages[j];
                    ages[j] = ages[j+1];
                    ages[j+1] = temp ;
                    flag = true ;
                }
            }
            System.out.println("-------");
        }
        for (int i = 0; i < 5; i++) {
            System.out.print(ages[i]+ "\t");
        }

法二

int[] ages = {1,2,3,4,5};
        boolean flag = true ;
        for (int i = 0; flag && i < ages.length-1; i++) {
            flag = false ;
            for (int j = 0; j < ages.length - i - 1; j++) {
                if(ages[j] > ages[j+1]){
                    int temp = ages[j];
                    ages[j] = ages[j+1];
                    ages[j+1] = temp ;
                    flag = true ;
                }

            }
            System.out.println("-----");
        }

        for (int i = 0; i < ages.length; i++) {
            System.out.print(ages[i]+"\t");
        }
— 于 共写了589个字
— 文内使用到的标签:

发表评论

电子邮件地址不会被公开。 必填项已用*标注