题解 | #冒泡排序优化#
冒泡排序
http://www.nowcoder.com/practice/83ef53227d654df28c18fd6a377e8fee
冒泡排序优化
优化点:
1.根据一轮后是否发生交换判断数组是否已经有序,若有序则提前结束
2.根据最后一次发生交换的位置界定数列有序区。
import java.util.Scanner;
public class Main {
// 冒泡排序算法
public static void bubbleSort(int[] array) {
int sortBorder = array.length - 1; // 无序数列边界
int lastExchangeIndex = 0; // 最后一次发生交换的位置
for(int x=1;x<=array.length-1;x++) {
boolean isSorted = true;
for(int y=0;y<sortBorder;y++) {
if(array[y]>array[y+1]) {
int temp = array[y];
array[y] = array[y+1];
array[y+1] = temp;
lastExchangeIndex = y;
isSorted = false;
}
}
sortBorder = lastExchangeIndex;
if(isSorted) break;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] arr = new int[7];
for (int i = 0; i < arr.length; i++) {
arr[i] = scanner.nextInt();
}
scanner.close();
//write your code here......
bubbleSort(arr);
for (int k = 0; k < arr.length; k++) {
System.out.print(arr[k]+" ");
}
}
}
