【排序】冒泡排序 & 快速排序

冒泡排序

思想

冒泡排序就是自上向下依次对比两个数字,若上面的数字大于下面的数字,则两者交换,否则不交换。这样每次循环结束,未排序的最大的数就到了最下面。

如数组{34, 8, 64, 51, 32, 21, 77, 2}前两次循环过程如下:
在这里插入图片描述

Java代码

class Sort{
	public static void main(String[] args) {
		int[] data = {34,8,64,51,32,21,77,2};
		bubbleSort(data);
		for(int x : data)
			System.out.print(x+" ");
		System.out.println();
	}
	public static void bubbleSort(int[] array) {
		int len = array.length;
		for(int i=0; i<len-1; i++) {
			for(int j=0; j<len-1-i; j++) {
				if(array[j] > array[j+1])
					swap(array, j, j+1);
			}
		}
	}
	public static void swap(int[] array,  int i, int j) {
		int temp = array[i];
		array[i] = array[j];
		array[j] = temp;
	}
}

快速排序

思想

快速排序的核心是partition()函数,其功能如下所示:
在这里插入图片描述
34的位置找到后,其将数组分成两部分,前一部分{2,8,21,32}都比34小,后一部分{61, 77, 64}都比34大。则利用递归对着两个子数组执行partition()方法。

Java代码

class Sort{
	public static void main(String[] args) {
		int[] data = {34,8,64,51,32,21,77,2};
		quickSort(data, 0, data.length-1);
		for(int x : data)
			System.out.print(x+" ");
		System.out.println();
	}
	public static void quickSort(int[] array, int start, int end) {
        if(end > start) {
        	int idx = partition(array, start, end);
        	quickSort(array, start, idx-1);
        	quickSort(array, idx+1, end);
        }
	}
	
	public static int partition(int[] input, int start, int end){
        int key = input[start];
        while(start < end){
            while(start<end && input[end]>=key)
                end--;
            swap(input, start, end);
            while(start<end && input[start]<=key)
                start++;
            swap(input, start, end);
        }
        return start;
    }

	public static void swap(int[] array,  int i, int j) {
		int temp = array[i];
		array[i] = array[j];
		array[j] = temp;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值