Java数组3种排序方法

一、数组封装好的排序方法         

    public static void main(String[] args) {

        int[] scores = { 30 , 28 , 33 , 47 , 25 ,21, 88 , 96 } ;
        Arrays.sort(scores) ;
        System.out.print("scores = { ");        
        for (int i = 0; i < scores.length; i++) {
            if(i<scores.length-1){
                System.out.print(scores[i] + ",");
            }
            if(i==scores.length-1){
                System.out.print(scores[i] + " }");
            }
        }

    

二、选择排序       

         选择排序若小到大排序,最先出现的是数组的最小元素出现在第一位,整体思想是用数组的第一个元素开始与数组的每一个元素依次对比,若第一位大于相比较的元素交换元素位子,第一轮比完最小值出现在第一位,然后用第二位依次与后面的元素对比

如下:         

    public static void main(String[] args) {

        int[] scores = { 30 , 28 , 33 , 47 , 25 ,21, 88 , 96 } ;

        System.out.print("scores = { ");     
        for(int i=0 ; i<scores.length; i++){

               for(int j=i+1 ; j <  scores.length-1   ;  j++){

                       int temp;

                     //利用临时变量交换元素

                      if( scores[i] >scores[j]) {

                          temp =  scores[i] ;

                          scores[i] = scores[j] ; 

                           scores[j] = temp ;

                      }

                }

              ​​​​​​​   if(i<scores.length-1){
                       System.out.print(scores[i] + ",");
                 }
                if(i==scores.length-1){
                    System.out.print(scores[i] + " }");
                }

 

​​​​​​​        }

​​​​​​​      }

三、冒泡排序   

         冒泡排序,就像水池底部产生气泡往水面山飘,和相邻的相比如前面的元素大于后面的元素,交换位置,最大的元素最先出现在最后一位。 代码如下:

public static void main(String[] args) {

        int[] scores = { 30 , 28 , 33 , 47 , 25 , 21 , 88 , 96 , 43} ;
        for(int i = 0 ; i<scores.length ; i++){
            for(int j = 0 ; j<scores.length-1 ; j++){
                int temp  ;

                 //利用临时变量交换元素
                if(scores[j] > scores[j+1]){
                    temp = scores[j] ;
                    scores[j] = scores[j+1] ;
                    scores[j+1] = temp;
                }
            }
  }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值