Debian Codegraph @

rhino/src/org/mozilla/javascript/Sorting.java

raw symbols SCIP
1 package org.mozilla.javascript;
2
3 import java.util.Arrays;
4 import java.util.Comparator;
5
6 public final class Sorting {
7 private static final int SMALLSORT = 16;
8
9 public static void insertionSort(Object[] a, Comparator<Object> cmp)
10 {
11 insertionSort(a, 0, a.length - 1, cmp);
12 }
13
14 public static void insertionSort(Object[] a, int start, int end, Comparator<Object> cmp)
15 {
16 int i = start;
17 while (i <= end) {
18 Object x = a[i];
19 int j = i - 1;
20 while ((j >= start) && (cmp.compare(a[j], x) > 0)) {
21 a[j + 1] = a[j];
22 j--;
23 }
24 a[j + 1] = x;
25 i++;
26 }
27 }
28
29 /*
30 Hybrid sorting mechanism similar to Introsort by David Musser. Uses quicksort's
31 partitioning mechanism recursively until the resulting array is small or the
32 recursion is too deep, and then use insertion sort for the rest.
33 This is the same basic algorithm used by the GNU Standard C++ library.
34 */
35 public static void hybridSort(Object[] a, Comparator<Object> cmp)
36 {
37 hybridSort(a, 0, a.length - 1, cmp, log2(a.length) * 2);
38 }
39
40 private static void hybridSort(Object[] a, int start, int end, Comparator<Object> cmp, int maxdepth)
41 {
42 if (start < end) {
43 if ((maxdepth == 0) || ((end - start) <= SMALLSORT)) {
44 insertionSort(a, start, end, cmp);
45 } else {
46 int p = partition(a, start, end, cmp);
47 hybridSort(a, start, p, cmp, maxdepth - 1);
48 hybridSort(a, p + 1, end, cmp, maxdepth - 1);
49 }
50 }
51 }
52
53 /*
54 Quicksort-style partitioning, using the Hoare partition scheme described on Wikipedia.
55 Use the "median of three" method to determine which index to pivot on, and then
56 separate the array into two halves based on the pivot.
57 */
58 private static int partition(Object[] a, int start, int end, Comparator<Object> cmp) {
59 Object pivot = a[median(start, end, start + ((end - start) / 2))];
60 int i = start - 1;
61 int j = end + 1;
62 while (true) {
63 do {
64 i++;
65 } while (cmp.compare(a[i], pivot) < 0);
66 do {
67 j--;
68 } while (cmp.compare(a[j], pivot) > 0);
69 if (i >= j) {
70 return j;
71 }
72 swap(a, i, j);
73 }
74 }
75
76 private static void swap(Object[] a, int l, int h)
77 {
78 Object tmp = a[l];
79 a[l] = a[h];
80 a[h] = tmp;
81 }
82
83 private static int log2(int n)
84 {
85 return (int)(Math.log10(n) / Math.log10(2.0));
86 }
87
88 private static int median(int n1, int n2, int n3)
89 {
90 int[] a = {n1, n2, n3};
91 Arrays.sort(a);
92 return a[1];
93 }
94 }