废话不多说,上解析图
package jzoffer;
import java.util.Scanner;
public class BubbleSort {
public static void main(String[] args) {
System.out.println("请输入你想排序的个数:");
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int a [] = new int[t];
int i = 0;
while(sc.hasNext()){
a[i] = sc.nextInt();
++i;
}
BubbleSort1(a);
BubbleSort2(a);
}
public static void BubbleSort1(int [] a){
if(a.length <= 0){
return;
}
for(int i = 0;i<a.length;i++){
for(int j = 1;j<a.length-i;j++){
if(a[j-1]>a[j]){
int temp = a[j-1];
a[j-1] = a[j];
a[j] = temp;
}
}
}
System.out.println("用没优化的冒泡排序方法执行结果如下:");
for(int i =0;i<a.length;i++){
System.out.print(a[i]+" ");
}
}
public static void BubbleSort2(int [] a){
if(a.length <= 0){
return;
}
boolean didSwap;
for(int i = 0;i<a.length;i++){
didSwap = false;//第一趟排序的时候先设置为false
for(int j = 1;j<a.length-i;j++){
if(a[j-1]>a[j]){
int temp = a[j-1];
a[j-1] = a[j];
a[j] = temp;
didSwap = true;
}
}
if(didSwap == false){
System.out.println("");
System.out.println("用优化后的冒泡排序方法执行结果如下:");
for(int j =0;j<a.length;j++){
System.out.print(a[j]+" ");
}
return;//看见了吗?小伙子,这个为什么会==false
} //因为如果是正序排列,比如1,2,3,4,5
} //它上面一直都没进入if语句里面去,所以到最后他是false可以直接返回
System.out.println("");//这样的话,他最好的时间复杂度就是n喽
System.out.println("用优化后的冒泡排序方法执行结果如下:");
for(int i =0;i<a.length;i++){
System.out.print(a[i]+" ");
}
}
}
