冒泡排序算法JAVA实现版

/**
*关于冒泡排序,从性能最低版本实现到性能最优版本实现
*/
public
class BubbleSortDemo { public static void sort(int array[]) { for (int i = 0; i < array.length - 1; i++) { //通过前面和后面对比,进行两两比对,复杂度是O(n2) for (int j = 0; j < array.length - i - 1; j++) { int temp = 0; if (array[j] > array[j + 1]) { //先临时存放左边最大的值 temp = array[j]; //把小的内容移动到左边 array[j] = array[j + 1]; //将左边最大的值往右移动一位 array[j + 1] = temp; } } } } public static void sortV2(int array[]) { for (int i = 0; i < array.length - 1; i++) { //有序标记,每一轮的初始值都是true boolean isSorted = true; for (int j = 0; j < array.length - i - 1; j++) { int temp = 0; if (array[j] > array[j + 1]) { temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; //因为有元素进行交互,所以不是有序的,标记变为false isSorted = false; } } if (isSorted) { break; } } } public static void sortV3(int array[]) { //记录最后一次交换的位置 int lastExchangeIndex = 0; //无序数列的边界,每次比较只需要比到这里就可以了 int sortBorder = array.length - 1; for (int i = 0; i < array.length - 1; i++) { //有序标记,每一轮的初始值都是true boolean isSorted = true; for (int j = 0; j < sortBorder; j++) { int temp = 0; if (array[j] > array[j + 1]) { temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; //因为有元素进行交互,所以不是有序的,标记变为false isSorted = false; //更新为最后一次交换元素的位置 lastExchangeIndex = j; } } sortBorder = lastExchangeIndex; if (isSorted) { break; } } } public static void main(String[] args) { // int[] array = new int[]{5, 8, 6, 3, 9, 2, 1, 7}; int[] array = new int[]{2, 1, 3, 4, 5, 6, 7, 8}; // sort(array); sortV3(array); System.out.println(Arrays.toString(array)); } }

猜你喜欢

转载自www.cnblogs.com/zhangfengshi/p/12808032.html