算法练习 (2) 快速排序

本文详细介绍了快速排序算法的基本思想和实现方式,包括递归版本和非递归版本的代码示例,并给出了具体的运行结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

算法描述

快速排序(Quicksort)是对冒泡排序的一种改进。

它的基本思想是:通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。

递归版:

    /*递归写法 10.3
	最好、平均时间复杂度O(NlogN) 空间复杂度O(logN)
	最差时间复杂度O(N*N) 空间复杂度O(N) 退化成冒泡排序
	不稳定*/
    public static void quicksort(int a[]){
		    quicksort(a, 0, a.length-1);
    }
    public static void quicksort(int a[], int low, int high){
		if (low > high) {
			return;
		}
		int i = low;
		int j = high;
		int index = a[low];
		while (i < j) {
			while (i<j && a[j]>=index) {
				j--;
			}
			if (i < j) {
				a[i++] = a[j];
			}
			while (i<j && a[i]<=index) {
				i++;
			}
			if (i < j) {
				a[j--] = a[i];
			}
			a[i] = index;
			quicksort(a, low, i-1);
			quicksort(a, i+1, high);
		}
	}
    public static void main(String[] args) {
        int a[] = { 49, 38, 65, 97, 76, 13, 27, 49,78 ,48646,4896,48,64,465,64 };
        quicksort(a);
        System.out.println(Arrays.toString(a));
    }

非递归版:

public static void quicksort(int a[]){
		int i,j,index,low,high,temp;
		Stack<Integer> stack = new Stack<Integer>();
		stack.push(0);
		stack.push(a.length-1);
		while (!stack.isEmpty()) {
			high = stack.pop();
			low = stack.pop();
			index = a[low];
			i = low;
			j = high;
			while (i<j) {
				while (i<j && a[j]>=index) {
					j--;
				}
				while (i<j && a[i]<=index) {
					i++;
				}
				temp = a[i];
				a[i] = a[j];
				a[j] = temp;
			}
			if (index > a[i]) {
				temp = a[low];
				a[low] = a[j];
				a[j] = temp;
			}
			if (low < i-1) {
				stack.push(low);
				stack.push(i-1);
			}
			if (high > i+1) {
				stack.push(i+1);
				stack.push(high);
			}
		}
	}

运行结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值