1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| package utils.sort;
public class TwoWayMergeSort implements Sort {
public void sort(int[] data) { int[] copy = new int[data.length]; for (int step = 1, i, j, alen, blen, pa, pb; step < data.length; step <<= 1) { for (i = 0, j = 0; i < data.length; ) { if (i + step < data.length) { System.arraycopy(data, i, copy, 0, step); alen = step; i += step; } else { System.arraycopy(data, i, copy, 0, data.length - i); alen = data.length - i; i = data.length; } if (i + step - 1 < data.length) { System.arraycopy(data, i, copy, data.length - step, step); blen = step; i += step; } else if (i < data.length) { System.arraycopy(data, i, copy, i, data.length - i); blen = data.length - i; i = data.length; } else blen = 0;
for (pa = 0, pb = data.length - blen; pa < alen && pb < data.length; ) { data[j++] = copy[pa] > copy[pb] ? copy[pb++] : copy[pa++]; } if (pa == alen) { System.arraycopy(copy, pb, data, j, data.length - pb); j += (data.length - pb); } else { System.arraycopy(copy, pa, data, j, alen - pa); j += (alen - pa); } } } } }
|