第一种:(从高到低)(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;
}
}