冒泡排序算法(三)

一、冒泡排序优化算法效率分析

通过上一篇文章分析我们明白了一件事,冒泡排序优化算法的时间复杂度取决与数据的好坏(也就是说数据是否在未排序之前就有了排序)

那么下面我们就来分析一下不同的数据对冒泡排序优化算法的影响

当只排序一次时:第二层循环只遍历两次

时间复杂度为O(n)

当数据全部逆序时:算法和简单冒泡排序算法一致

时间复杂度为O(n^2)

据此我们可分析出此算法的平均时间复杂度为O(n^2)

接下来我们再来分析一个小问题,为什么真正排序了一次我们第二层循环却还要跑两趟呢?

我们仔细分析我们第一趟比较完了,程序还没有结束,因为此时的flag还没有被置为false,所以我们还需要跑一趟。

二、代码运行结果对比
class MaoPaoSort {
    void maoPaoSort(int[] array) {
        for (int i = 0; i < array.length - 1; i++) {
            for (int j = 0; j < array.length - 1 - i; j++) {
                if (array[j] > array[j + 1]) {
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
        }
    }

    void maoPaoSortOptimized(int[] array) {

        int count = 0;
        for (int i = 0; i < array.length - 1; i++) {
            boolean flag = false;
            count++;
            for (int j = 0; j < array.length - 1 - i; j++) {
                if (array[j] > array[j + 1]) {
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                    flag = true;  //说明发生了交换,那么此时将标志位flag设置位true说明发生了交换
                }
            }
            if (!flag)   //在每一趟(也就是第一层循环的每一次循环)都判断flag的值,如果flag为false,也就是说这一趟数据无任何交换,那么就说明数据已经被排好了,不需要再进行循环了
                break;
        }
        System.out.println("共走了"+count+"趟");
    }
}




import java.util.Arrays;

public class Sort {
    public static void main(String[] args) {
        int[] ints = {2, 34, 4, 55, 88};
        MaoPaoSort maoPaoSort = new MaoPaoSort();
        maoPaoSort.maoPaoSort(ints);
        System.out.println("简单冒泡排序" + Arrays.toString(ints));

        int[] ints1 = {88, 2, 4, 34, 55};
        maoPaoSort.maoPaoSortOptimized(ints1);
        System.out.println("优化冒泡排序" + Arrays.toString(ints1));
    }
}

简单冒泡排序[2, 4, 34, 55, 88]
共走了2趟
优化冒泡排序[2, 4, 34, 55, 88]
原文地址:https://www.cnblogs.com/shisanyue/p/13510180.html