cnblogs 測試頁面
這是一個測試頁面
1 /** 2 * <html> 3 * <body> 4 * <P> Copyright 1994-2018 JasonInternational </p> 5 * <p> All rights reserved.</p> 6 * <p> Created on 2018年4月10日 </p> 7 * <p> Created by Jason</p> 8 * </body> 9 * </html> 10 */ 11 package cn.ucaner.algorithm.sorts; 12 13 import java.util.Random; 14 15 /** 16 * Quicksort is a sorting algorithm which, on average, makes O(n*log n) comparisons to sort 17 * n items. In the worst case, it makes O(n^2) comparisons, though this behavior is 18 * rare. Quicksort is often faster in practice than other algorithms. 19 * <p> 20 * Family: Divide and conquer.<br> 21 * Space: In-place.<br> 22 * Stable: False.<br> 23 * <p> 24 * Average case = O(n*log n)<br> 25 * Worst case = O(n^2)<br> 26 * Best case = O(n) [three-way partition and equal keys]<br> 27 * <p> 28 * @see <a href="https://en.wikipedia.org/wiki/Quick_sort">Quicksort (Wikipedia)</a> 29 * <br> 30 * @author Justin Wetherell <phishman3579@gmail.com> 31 */ 32 public class QuickSort<T extends Comparable<T>> { 33 34 private static final Random RAND = new Random(); 35 36 public static enum PIVOT_TYPE { 37 FIRST, MIDDLE, RANDOM 38 } 39 40 public static PIVOT_TYPE type = PIVOT_TYPE.RANDOM; 41 42 private QuickSort() { } 43 44 public static <T extends Comparable<T>> T[] sort(PIVOT_TYPE pivotType, T[] unsorted) { 45 int pivot = 0; 46 if (pivotType == PIVOT_TYPE.MIDDLE) { 47 pivot = unsorted.length/2; 48 } else if (pivotType == PIVOT_TYPE.RANDOM) { 49 pivot = getRandom(unsorted.length); 50 } 51 sort(pivot, 0, unsorted.length - 1, unsorted); 52 return unsorted; 53 } 54 55 private static <T extends Comparable<T>> void sort(int index, int start, int finish, T[] unsorted) { 56 int pivotIndex = start + index; 57 T pivot = unsorted[pivotIndex]; 58 int s = start; 59 int f = finish; 60 while (s <= f) { 61 while (unsorted[s].compareTo(pivot) < 0) 62 s++; 63 while (unsorted[f].compareTo(pivot) > 0) 64 f--; 65 if (s <= f) { 66 swap(s, f, unsorted); 67 s++; 68 f--; 69 } 70 } 71 if (start < f) { 72 pivotIndex = getRandom((f - start) + 1); 73 sort(pivotIndex, start, f, unsorted); 74 } 75 if (s < finish) { 76 pivotIndex = getRandom((finish - s) + 1); 77 sort(pivotIndex, s, finish, unsorted); 78 } 79 } 80 81 private static final int getRandom(int length) { 82 if (type == PIVOT_TYPE.RANDOM && length > 0) 83 return RAND.nextInt(length); 84 if (type == PIVOT_TYPE.FIRST && length > 0) 85 return 0; 86 return length / 2; 87 } 88 89 private static <T extends Comparable<T>> void swap(int index1, int index2, T[] unsorted) { 90 T index2Element = unsorted[index1]; 91 unsorted[index1] = unsorted[index2]; 92 unsorted[index2] = index2Element; 93 } 94 }