| 1 |
/* |
| 2 |
* Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0, |
| 3 |
* and the EPL 1.0 (https://h2database.com/html/license.html). |
| 4 |
* Initial Developer: H2 Group |
| 5 |
*/ |
| 6 |
package org.h2.dev.util; |
| 7 |
|
| 8 |
import java.util.Comparator; |
| 9 |
|
| 10 |
/** |
| 11 |
* Array utility methods. |
| 12 |
*/ |
| 13 |
public class ArrayUtils { |
| 14 |
|
| 15 |
/** |
| 16 |
* Sort an array using binary insertion sort |
| 17 |
* |
| 18 |
* @param <T> the type |
| 19 |
* @param d the data |
| 20 |
* @param left the index of the leftmost element |
| 21 |
* @param right the index of the rightmost element |
| 22 |
* @param comp the comparison class |
| 23 |
*/ |
| 24 |
public static <T> void binaryInsertionSort(T[] d, int left, int right, |
| 25 |
Comparator<T> comp) { |
| 26 |
for (int i = left + 1; i <= right; i++) { |
| 27 |
T t = d[i]; |
| 28 |
int l = left; |
| 29 |
for (int r = i; l < r;) { |
| 30 |
int m = (l + r) >>> 1; |
| 31 |
if (comp.compare(t, d[m]) >= 0) { |
| 32 |
l = m + 1; |
| 33 |
} else { |
| 34 |
r = m; |
| 35 |
} |
| 36 |
} |
| 37 |
for (int n = i - l; n > 0;) { |
| 38 |
d[l + n--] = d[l + n]; |
| 39 |
} |
| 40 |
d[l] = t; |
| 41 |
} |
| 42 |
} |
| 43 |
|
| 44 |
/** |
| 45 |
* Sort an array using insertion sort |
| 46 |
* |
| 47 |
* @param <T> the type |
| 48 |
* @param d the data |
| 49 |
* @param left the index of the leftmost element |
| 50 |
* @param right the index of the rightmost element |
| 51 |
* @param comp the comparison class |
| 52 |
*/ |
| 53 |
public static <T> void insertionSort(T[] d, int left, int right, |
| 54 |
Comparator<T> comp) { |
| 55 |
for (int i = left + 1, j; i <= right; i++) { |
| 56 |
T t = d[i]; |
| 57 |
for (j = i - 1; j >= left && comp.compare(d[j], t) > 0; j--) { |
| 58 |
d[j + 1] = d[j]; |
| 59 |
} |
| 60 |
d[j + 1] = t; |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
|
| 65 |
} |