Implements a Mergesort. - Java Data Structure

Java examples for Data Structure:Sort

Description

Implements a Mergesort.

Demo Code


class Merge {//from  www. ja  v a 2 s. c  o m

  private static Comparable[] compara;

  private static boolean less(Comparable v, Comparable w) {
    return v.compareTo(w) < 0;
  }

  public static boolean isSorted(Comparable[] a) {
    for (int i = 1; i < a.length; i++)
      if (less(a[i], a[i - 1]))
        return false;

    return true;
  }

  private static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) {
    // copy the array
    for (int k = lo; k <= hi; k++)
      aux[k] = a[k];

    int i = lo, j = mid + 1;

    for (int k = lo; k <= hi; k++) {
      if (i > mid)
        a[k] = aux[j++];
      else if (j > hi)
        a[k] = aux[i++];
      else if (less(aux[j], aux[i]))
        a[k] = aux[j++];
      else
        a[k] = aux[i++];
    }
  }

  private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) {
    if (hi <= lo)
      return;

    int mid = lo + (hi - lo) / 2; // split the array in 2 parts

    sort(a, aux, lo, mid); // left
    sort(a, aux, mid + 1, hi); // right

    merge(a, aux, lo, mid, hi);
  }

  public static void sort(Comparable[] a) {
    compara = new Comparable[a.length];

    sort(a, compara, 0, a.length - 1);
  }

  public static void main(String[] args) {
    Integer[] data = new Integer[] { 5, 1, 3, 7, 4, 8, 1, 38, 10, 9, 8, 44 };
    sort(data);

    System.out.print("Array sorted by Mergesort: ");
    for (Integer x : data) {
      System.out.printf("%s ", x);
    }
  }

}

Related Tutorials