1 2 12 package com.versant.core.common; 13 14 26 public abstract class SortableBase { 27 28 31 protected int size; 32 33 36 public void sort() { 37 quicksort(0, size - 1); 38 } 39 40 public void sort(int min, int max){ 41 quicksort(min,max); 42 } 43 47 protected abstract int compare(int a, int b); 48 49 52 protected abstract void swap(int index1, int index2); 53 54 private final void quicksort(final int left,final int right) { 55 final int size = right - left + 1; 56 if (size <= 3) { 57 manualSort(left, right, size); 58 } else { 59 final int median = median(left, right); 60 final int partition = partition(left, right, median); 61 quicksort(left, partition - 1); 62 quicksort(partition + 1, right); 63 } 64 } 65 66 69 private final void manualSort(final int left, final int right,final int size) { 70 if (size <= 1) return; 71 if (size == 2) { 72 if (compare(left, right) > 0) swap(left, right); 73 } else { 74 if (compare(left, right - 1) > 0) swap(left, right - 1); 75 if (compare(left, right) > 0) swap(left, right); 76 if (compare(left + 1, right) > 0) swap(left + 1, right); 77 } 78 79 } 80 81 private final int median(final int left,final int right) { 82 final int center = (left + right) / 2; 83 if (compare(left, center) > 0) swap(left, center); 84 if (compare(left, right) > 0) swap(left, right); 85 if (compare(center, right) > 0) swap(center, right); 86 swap(center, right - 1); 87 return right - 1; 88 } 89 90 private final int partition(final int left,final int right,final int pivotIndex) { 91 int leftIndex = left; 92 int rightIndex = right - 1; 93 while (true) { 94 while (compare(++leftIndex, pivotIndex) < 0); 95 while (compare(--rightIndex, pivotIndex) > 0); 96 if (leftIndex >= rightIndex) { 97 break; } else { 99 swap(leftIndex, rightIndex); 100 } 101 } 102 swap(leftIndex, right - 1); return leftIndex; } 105 106 } 107 108 | Popular Tags |