冒泡排序两种方式实现

第一种:(从高到低)(Integer的用法,里面包含的是: 关于循环的长度问题。从低到高和从高到低;Integer的compareTo 的用法;)


public class bubbleSort {
 public static void main(String [] args){
  Integer  a[]={4,2,1,6,3,6,0,-5,1,1};
  bubbleSort(a,0,a.length-1);
  for(int i=0;i<a.length ;i++){
   System.out.println(a[i]);
  }
 }
    public static void bubbleSort(Integer [] a,int from,int end){
     Boolean exchange;
     for(int i=1;i<end-from+1;i++){
      for(int j=end-from;j>=i;j--){      
       if(a[j].compareTo(a[j-1])<0){
       exchange=false;
       swap(a,j,j-1); 
       }    
      }
     }
    }
    public static void swap(Integer []a,int x,int y){
     Integer temp=a[x];
     a[x]=a[y];
     a[y]=temp;
    }
}

 

第二种:(从低到高,int 版的哦)

 

public class bubbleSort{
 public static void main(String []args){
  int a[]={4,6,2,6,8,1,9,7,0};
  bubbleSort(a);
  for(int i=0;i<a.length;i++){
   System.out.println(a[i]);
  }
 }
 public static void bubbleSort(int []a){
  for(int i=a.length -1;i>0;i--){
   for(int j=0;j<i;j++){
    if(new Integer(a[j]).compareTo(new Integer(a[j+1]))>0){
     swap(a,j,j+1);
    }
   }
  }
 }
 public static void swap(int []a,int x,int y){
    int temp=a[x];
    a[x]=a[y];
    a[y]=temp;
 }
}

 

 第三种(属于优化的种类,多了一个变量来表示用不用在一个循环中再继续下去)

/Integer 版的
public class bubbleSort{
 static Boolean exchange;
 public static void main(String []args){
  Integer []arr={4,6,2,6,8,1,9,7,0};
  bubbleSort(arr,0,arr.length-1);
  for(int i=0;i<arr.length;i++){
   System.out.println(arr[i]);
  }
  
 }
 public static void bubbleSort(Integer []arr,int from ,int end ){
  for(int i = 1;i<end-from+1;i++){
   exchange=false;
   for(int j=end-from;j>=i;j--){
    if(arr[j].compareTo(arr[j-1])<0){
     swap(arr,j,j-1);
    }
   }
   if(!exchange){
    return;
   }
  }
 }
 public static boolean swap(Integer arr[],int x,int y){
  Integer temp=arr[x];
  arr[x]=arr[y];
  arr[y]=temp;
  exchange=true;
  return exchange;
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值