20 namespace Lucene.Net.Util
28 private const int MERGESORT_THRESHOLD = 12;
29 private const int QUICKSORT_THRESHOLD = 7;
31 abstract protected internal void Swap(
int i,
int j);
32 abstract protected internal int Compare(
int i,
int j);
34 public virtual void QuickSort(
int lo,
int hi)
36 QuickSortHelper(lo, hi);
37 InsertionSort(lo, hi);
40 private void QuickSortHelper(
int lo,
int hi)
45 if (diff <= QUICKSORT_THRESHOLD)
49 int i = (hi + lo) / 2;
50 if (Compare(lo, i) > 0)
54 if (Compare(lo, hi) > 0)
58 if (Compare(i, hi) > 0)
68 while (Compare(++i, v) < 0)
72 while (Compare(--j, v) > 0)
83 if (j - lo <= hi - i + 1)
85 QuickSortHelper(lo, j);
90 QuickSortHelper(i + 1, hi);
96 private void InsertionSort(
int lo,
int hi)
98 for (
int i = lo + 1; i <= hi; i++)
100 for (
int j = i; j > lo; j--)
102 if (Compare(j - 1, j) > 0)
114 protected internal virtual void MergeSort(
int lo,
int hi)
117 if (diff <= MERGESORT_THRESHOLD)
119 InsertionSort(lo, hi);
122 int mid = lo + diff / 2;
125 Merge(lo, mid, hi, mid - lo, hi - mid);
128 private void Merge(
int lo,
int pivot,
int hi,
int len1,
int len2)
130 if (len1 == 0 || len2 == 0)
134 if (len1 + len2 == 2)
136 if (Compare(pivot, lo) < 0)
142 int first_cut, second_cut;
147 first_cut = lo + len11;
148 second_cut = Lower(pivot, hi, first_cut);
149 len22 = second_cut - pivot;
154 second_cut = pivot + len22;
155 first_cut = Upper(lo, pivot, second_cut);
156 len11 = first_cut - lo;
158 Rotate(first_cut, pivot, second_cut);
159 int new_mid = first_cut + len22;
160 Merge(lo, first_cut, new_mid, len11, len22);
161 Merge(new_mid, second_cut, hi, len1 - len11, len2 - len22);
164 private void Rotate(
int lo,
int mid,
int hi)
172 lot = mid; hit = hi - 1;
177 lot = lo; hit = hi - 1;
184 private int Lower(
int lo,
int hi,
int val)
191 if (Compare(mid, val) < 0)
194 len = len - half - 1;
204 private int Upper(
int lo,
int hi,
int val)
211 if (Compare(val, mid) < 0)
218 len = len - half - 1;