Java Array Merge merge(int[] a, int l, int m, int h)

Here you can find the source of merge(int[] a, int l, int m, int h)

Description

Merge the sorted sub-array a[l:m] with the sorted sub-array a[m+1:h], Cormen's single loop merge.

License

Open Source License

Declaration

public static void merge(int[] a, int l, int m, int h) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**//  w w  w .  j ava 2s.  c om
     * Merge the sorted sub-array a[l:m] with the sorted sub-array a[m+1:h],
     * Cormen's single loop merge.
     */
    public static void merge(int[] a, int l, int m, int h) {
        // Scheme:
        // put a[l:m]   in L[0:m-l],   put inf in L[m-l+1]
        // put a[m+1:h] in R[0:h-m-1], put inf in R[h-m]
        int[] L = new int[m - l + 2];
        int[] R = new int[h - m + 1];
        for (int i = l; i <= m; i++) {
            L[i - l] = a[i];
        }
        L[m - l + 1] = Integer.MAX_VALUE;
        for (int i = m + 1; i <= h; i++) {
            R[i - m - 1] = a[i];
        }
        R[h - m] = Integer.MAX_VALUE;

        int j = 0, k = 0;
        for (int i = l; i <= h; i++) {
            if (L[j] <= R[k]) {
                a[i] = L[j];
                j++;
            } else {
                a[i] = R[k];
                k++;
            }
        }
    }

    /**
     * Merge the sorted sub-array a[l:m] with the sorted sub-array a[m+1:h],
     * using temp as a temporary array.
     */
    public static void merge(int[] a, int[] temp, int l, int m, int h) {
        if (temp.length < h - l + 1) {
            throw new IllegalArgumentException();
        }

        // i1 cursor over a[l:m]
        // i2 cursor over a[m+1:h]
        int i1 = l, i2 = m + 1;
        int j = l;
        while (i1 <= m && i2 <= h) {
            if (a[i1] < a[i2]) {
                temp[j++] = a[i1++];
            } else {
                temp[j++] = a[i2++];
            }
        }
        // Copy remaining.
        while (i1 <= m) {
            temp[j++] = a[i1++];
        }
        while (i2 <= h) {
            temp[j++] = a[i2++];
        }

        // Copy temp[] to a[]
        j = l;
        for (int i = l; i <= h; i++, j++) {
            a[i] = temp[j];
        }
    }
}

Related

  1. merge(E[] arrayA, E[] arrayB)
  2. merge(final byte[] b1, final byte[] b2)
  3. merge(final byte[]... data)
  4. merge(final String[] array1, final String[] array2)
  5. merge(final T[] array1, final T[] array2)
  6. merge(int[] a, int[] b)
  7. merge(int[] a, int[] b)
  8. merge(int[] a, int[] temp, int fromIndex, int toIndex)
  9. merge(int[] array, int i, int mid, int max)