排序算法-冒泡排序

稳定性

       假定在待排序的记录序列中,存在多个具有相同的关键字的记录,若经过排序,这些记录的相对次序保持不变,即在原序列中,r[i]=r[j],且r[i]在r[j]之前,而在排序后的序列中,r[i]仍在r[j]之前,则称这种排序算法是稳定的;否则称为不稳定的。即存在相等的数据,它们的相对顺序不会发生改变。

package sortalgorithm.bubblesort;

import com.alibaba.fastjson.JSON;
import java.util.Arrays;
import java.util.List;

/**
 * @author whale_fall
 * @Description 冒泡排序
 * @date 2022/11/13
 */
public class BubbleSort {

    /**
     * 冒泡排序
     * 描述:依次比较两个数,较大的数往后移动,
     * 每次排序后都可以找到一个相对大的数放在最后,所以每次排序后后面的是有序的
     * 时间复杂度为:平均时间复杂度:O(n^2);最好的情况:O(n)
     * 空间复杂度为:O(1)
     * 是否是稳定的:是
     *
     * @param args
     */
    public static void main(String[] args) {
        List<Integer> tempList = Arrays.asList(new Integer[]{3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48});
        bubbleSort1(tempList);
        bubbleSort2(tempList, tempList.size());
        System.out.println(JSON.toJSONString(tempList));
    }

    private static void bubbleSort1(List<Integer> tempList) {
        int len = tempList.size();
        for (int j = 0; j < len; j++) {
            for (int i = 0; i < len -j- 1; i++) {
                int curr = tempList.get(i);
                int next = tempList.get(i + 1);
                if (curr > next) {
                    tempList.set(i + 1, curr);
                    tempList.set(i, next);
                }
            }
        }
        System.out.println(JSON.toJSONString(tempList));
    }

    private static void bubbleSort2(List<Integer> tempList, int len) {
        if (len < 2) return;
        for (int i = 0; i < len - 1; i++) {
            int curr = tempList.get(i);
            int next = tempList.get(i + 1);
            if (curr > next) {
                tempList.set(i + 1, curr);
                tempList.set(i, next);
            }
        }
        bubbleSort2(tempList, len - 1);
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值