java quick_Java QuickSort 快速排序

/**

*

*

*

Copyright 1994-2018 JasonInternational

*

All rights reserved.

*

Created on 2018年4月10日

*

Created by Jason

*

*

*/

package cn.ucaner.algorithm.sorts;

import java.util.Random;

/**

* Quicksort is a sorting algorithm which, on average, makes O(n*log n) comparisons to sort

* n items. In the worst case, it makes O(n^2) comparisons, though this behavior is

* rare. Quicksort is often faster in practice than other algorithms.

*

* Family: Divide and conquer.

* Space: In-place.

* Stable: False.

*

* Average case = O(n*log n)

* Worst case = O(n^2)

* Best case = O(n) [three-way partition and equal keys]

*

* @see Quicksort (Wikipedia)

*

* @author Justin Wetherell

*/

public class QuickSort> {

private static final Random RAND = new Random();

public static enum PIVOT_TYPE {

FIRST, MIDDLE, RANDOM

}

public static PIVOT_TYPE type = PIVOT_TYPE.RANDOM;

private QuickSort() { }

public static > T[] sort(PIVOT_TYPE pivotType, T[] unsorted) {

int pivot = 0;

if (pivotType == PIVOT_TYPE.MIDDLE) {

pivot = unsorted.length/2;

} else if (pivotType == PIVOT_TYPE.RANDOM) {

pivot = getRandom(unsorted.length);

}

sort(pivot, 0, unsorted.length - 1, unsorted);

return unsorted;

}

private static > void sort(int index, int start, int finish, T[] unsorted) {

int pivotIndex = start + index;

T pivot = unsorted[pivotIndex];

int s = start;

int f = finish;

while (s <= f) {

while (unsorted[s].compareTo(pivot) < 0)

s++;

while (unsorted[f].compareTo(pivot) > 0)

f--;

if (s <= f) {

swap(s, f, unsorted);

s++;

f--;

}

}

if (start < f) {

pivotIndex = getRandom((f - start) + 1);

sort(pivotIndex, start, f, unsorted);

}

if (s < finish) {

pivotIndex = getRandom((finish - s) + 1);

sort(pivotIndex, s, finish, unsorted);

}

}

private static final int getRandom(int length) {

if (type == PIVOT_TYPE.RANDOM && length > 0)

return RAND.nextInt(length);

if (type == PIVOT_TYPE.FIRST && length > 0)

return 0;

return length / 2;

}

private static > void swap(int index1, int index2, T[] unsorted) {

T index2Element = unsorted[index1];

unsorted[index1] = unsorted[index2];

unsorted[index2] = index2Element;

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值