冒泡排序(bubble sort)

冒泡排序也是简单的排序算法之一,算法复杂度为O(n^2),最优情况也是O(n^2)。突然发现自己以前做错了一道题。。。


csdn好像出bug了,不能显示我的全部内容。为了能显示全部内容,我只能一句话一个enter了。

算法简介
冒泡,bubbling。顾名思义就是大的气泡升的高?感觉很难理解。
我觉得冒泡排序还不如叫做沉淀排序。
当我们的试管中有n中不同密度,且互不相容的液体时。
密度越大的沉在越下面。请看下面一段伪代码:
BubbleSort(A)
for i ←1to length[A]
do for j length[A] downto i + 1
do if A[j] < A[j-1]
then exchange A[j] ↔ A[j -1]

解释:看了上面的代码,你是否也觉得冒泡排序应该改为沉淀排序?
外层循环一共执行n次。
每次(第i次):把A[i]到A[n](假设数组从1开始)中最小的数,
沉淀到A[i]。
因为无论什么情况,第i次一定会进行n-i次比较,
所以算法的最好情况也是O(n^2)。
代码
package sorting;

public class Data {
	
	/**
	 * generate an unsorted array of length n
	 * @param n length
	 * @param max the maximum integer element of this array
	 * @return an unsorted array consists of elements range from 1 to max
	 */
	public static int[] getArray(int n, int max){
		int[] result = new int[n];
		for(int i =0; i < n; i++){
			result[i] = (int)(Math.random() * max + 1);
		}
		return result;
	}
	/**
	 * print the array
	 * @param arg array
	 */
	public static void printArray(int[] arg){
		StringBuffer temp = new StringBuffer();
		for(int i = 0; i < arg.length; i++){
			temp.append(arg[i] + "\t");
		}
		System.out.println(temp);
	}
}
package sorting;

public class BubbleSort {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		BubbleSort bs = new BubbleSort();
		int[] data = Data.getArray(10, 100);
		System.out.print("Source data:\t");
		Data.printArray(data);
		bs.bubbleSort(data);
		System.out.print("Sorted data:\t");
		Data.printArray(data);
	}

	public void bubbleSort(int[] arg){
		int j = 0;
		int temp = 0;
		for(int i = 0;  i < arg.length; i++){
			j = arg.length - 1;
			while(j > i){
				if(arg[j] < arg[j - 1]){
					temp = arg[j];
					arg[j] = arg[j - 1];
					arg[j - 1] = temp;
				}
				j--;
			}
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值