排序算法总结(含动图演示和Java代码实现)

本文将围绕冒泡排序、桶排序、计数排序、堆排序、插入排序、并归排序、快速排序和选择排序,按照描述、时间复杂度(最坏情况)、动态图展示和代码实现来讲解。本文默认排序为从小到大。

本文相关代码已上传至github,欢迎关注https://github.com/zhuzhenke/common-algorithms

公用方法

SortUtils

public class SortUtils {

    public static void check(int[] sortingData) {
        if (sortingData == null || sortingData.length == 0) {
            throw new IllegalArgumentException("sortingData can not be empty!");
        }
    }

    public static void swap(int[] swapArray, int i, int j) {
        check(swapArray);
        if (i < 0 || i > swapArray.length - 1) {
            throw new ArrayIndexOutOfBoundsException("illegal index i:" + i);
        }
        if (j < 0 || j > swapArray.length - 1) {
            throw new ArrayIndexOutOfBoundsException("illegal index j:" + j);
        }
        int temp = swapArray[i];
        swapArray[i] = swapArray[j];
        swapArray[j] = temp;
    }

    public static int getMaxValue(int[] sortingData) {
        check(sortingData);

        int max = sortingData[0];
        for (int value : sortingData) {
            if (value < 0) {
                throw new IllegalArgumentException("value could not be negative:" + value);
            }
            if (value > max) {
                max = value;
            }
        }
        return max;
    }
}

冒泡排序

描述
  • 比较前后两个数的大小,如果前者大于后者,则交换两个数的位置
  • 最大的数字在进行一轮比较和交换后,会出现在数组的最后一个位置
  • 每一轮之后,可减少最大数字的比较。重复上述操作直到没有需要比较的元素为止
时间复杂度

O(n^2)

动态图展示

冒泡排序

代码实现

github代码

public int[] sort(int[] sortingData) {
        SortUtils.check(sortingData);
        for (int j = sortingData.length - 1; j > 0; j--) {
            for (int i = 0; i < j; i++) {
                if (sortingData[i] > sortingData[i + 1]) {
                    SortUtils.swap(sortingData, i, i + 1);
                }
            }
        }
        return sortingData;
    }

桶排序

描述
  • 挑选数组中最大的数字,设置默认分配的桶数,得到每个桶容纳的数字范围。如最大是10,桶是4个,则每个桶最大容纳3个数字。第0个桶放0、1、2、3,第1个桶方4、5、6,第2桶方7,8,9,以此类推
  • 对每个桶内进行冒泡排序或选择排序
  • 遍历所有桶,依次取出每个桶中的元素,得到的就是一个排好序的数组
时间复杂度

O(n^2)

动态图展示

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值