快速排序

基本思想:

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

快速排序是一种不稳定的排序方法,最差情况下其时间复杂度为O(n²),最好情况下为O(n logn),所以平均时间复杂度为O(n lg n/lg 2);

代码:

package book;

import java.util.Scanner;

public class SMC {
	public static void qsort_asc(int source[], int low, int high) {
		int i, j, x;
		if (low < high) {
			i = low;
			j = high;
			x = source[i];
			while (i < j) {
				while (i < j && source[j] > x) {
					j--;
				}
				if (i < j) {
					source[i] = source[j];
					i++;
				}
				while (i < j && source[i] < x) {
					i++;
				}
				if (i < j) {
					source[j] = source[i];
					j--;
				}
			}
			source[i] = x;
			qsort_asc(source, low, i - 1);
			qsort_asc(source, i + 1, high);
		}
	}

	public static void main(String[] args) {
		// int[] a = { 4, 2, 1, 6, 3, 6, 0, -5, 1, 1 };
		System.out.println("请输入数组的大小:");
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int a[] = new int[n];
		System.out.println("请输入数组的元素:");
		for (int i = 0; i < a.length; i++) {
			a[i] = sc.nextInt();
		}
		sc.close();
		int i;
		qsort_asc(a, 0, a.length - 1);
		System.out.println("最终的排序为:");
		for (i = 0; i < a.length; i++) {
			System.out.print(a[i] + "  ");
		}
	}
}

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值