【基础算法】排序-简单排序之一(冒泡排序)

本文详细介绍了冒泡排序的两种实现方式:向上冒泡排序和向下冒泡排序,分别阐述了它们的工作原理,时间复杂度,并提供了相应的代码实现。冒泡排序是一种简单的排序算法,虽然效率较低,但在特定情况下仍有其应用价值。
摘要由CSDN通过智能技术生成

一, 向上冒泡排序

元素从底向上冒,最轻的冒到最上边,最沉的冒到最下边。

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

证明如下

first element compare N-1

second element compare N-2

...

last element compare 0

total compares: [(0+1+...+N-1)*N]/2=(N^2)/2


实施代码

	public static void bubbleSortUp(int[] array) {
		for (int i = 0; i < array.length; i++) {
			for (int j = array.length - 1; j > i; j--) {
				if (more(array[j - 1], array[j]))
					exchange(array, j, j - 1);
			}
		}
	}


compare and exchange

	// compare
	public static boolean more(int v, int w) {
		return v > w;
	}

	// exchange
	public static void exchange(int[] array, int i, int j) {
		int temp = array[i];
		array[i] = array[j];
		array[j] = temp;
	}


二,向下冒泡排序

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值