冒泡排序作为最基本的排序方式,可以进行多次优化。
import java.util.*;
public class hello {
public static void main(String[] args){
int [] arr = {25,32,12,26,65,98,76};
int temp; //用于交换时候使用的中间变量
boolean fin = true; //用于判断排序是否提前结束,如果提前结束就终止
for(int i=0;i<arr.length-1;i++){
fin = true;
for(int j=0;j<arr.length-1-i;j++){
if(arr[j]>arr[j+1]){
fin = false;
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
if(fin){
break;
}
}
for(int i=0;i<arr.length;i++){
System.out.println(" "+arr[i]);
}
}
}
import java.util.*;
public class hello {
public static void main(String[] args){
int [] arr = {25,32,12,26,65,98,76};
int temp; //用于交换时候使用的中间变量
boolean fin = true; //用于判断排序是否提前结束,如果提前结束就终止
for(int i=0;i<arr.length-1;i++){
fin = true;
for(int j=0;j<arr.length-1-i;j++){
if(arr[j]>arr[j+1]){
fin = false;
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
if(fin){
break;
}
}
for(int i=0;i<arr.length;i++){
System.out.println(" "+arr[i]);
}
}
}