Java 快速排序

19 篇文章 0 订阅
15 篇文章 0 订阅

package com.algorithms;

import java.util.Arrays;
import java.util.Random;

public class QuickSort {
	
	private static int count = 0;
	
	public static  void quickSort(Integer[] arr, int l, int r) {
		if(l < r) {
			int p = randomPartition(arr, l, r);
			quickSort(arr, l, p - 1);
			quickSort(arr, p + 1, r);
		}
	}
	
	public static int randomPartition(Integer[] arr, int l, int r) {
		int p = getRandomIndex(l, r);
		exchange(arr, p, r);
		return partition(arr, l, r);
	}
	
	public static int partition(Integer[] arr, int l, int r) {
		int x = arr[r];
		int i = l - 1;
		for(int j = l; j < r; j++) {
			count++;
			if(arr[j] <= x) {
				i = i + 1;
				exchange(arr, i , j);
			}
		}
		exchange(arr, i + 1, r);
		return i + 1;
	}
	
	public static void exchange(Integer[] arr, int x, int y) {
		int temp = 0;
		temp = arr[x];
		arr[x] = arr[y];
		arr[y] = temp;
	}
	
	public static int getRandomIndex(int min, int max) {
        Random random = new Random(37);
        return random.nextInt(max)%(max-min+1) + min;
	}

	public static void main(String[] args) {
		Integer arr[] = {12, 2, 10, 16, 5, 6, 8, 1, 9, 18};
//		Integer arr[] = new Integer[30000000];
//		Random random = new Random(37);
//		for(int i = 0; i < 30000000; i++) {
//			arr[i] = random.nextInt(100000000)%(100000000 - 0 + 1)  + 0;
//		}
		quickSort(arr, 0, arr.length - 1);
		System.out.println(Arrays.asList(arr));
		System.out.println(count);
	}

}
其中getRandomIndex的作用是使排序达到期望的时间复杂度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值