Generic Merge Sorter with generic Comparator : Sort « Collections « Java Tutorial

Home
Java Tutorial
1.Language
2.Data Type
3.Operators
4.Statement Control
5.Class Definition
6.Development
7.Reflection
8.Regular Expressions
9.Collections
10.Thread
11.File
12.Generics
13.I18N
14.Swing
15.Swing Event
16.2D Graphics
17.SWT
18.SWT 2D Graphics
19.Network
20.Database
21.Hibernate
22.JPA
23.JSP
24.JSTL
25.Servlet
26.Web Services SOA
27.EJB3
28.Spring
29.PDF
30.Email
31.J2ME
32.J2EE Application
33.XML
34.Design Pattern
35.Log
36.Security
37.Apache Common
38.Ant
39.JUnit
Java Tutorial » Collections » Sort 
9.53.6.Generic Merge Sorter with generic ComparatorPrevious/Next
import java.util.Comparator;


public class AnimationTester {
  public static void main(String[] args) {

    Integer[] values = new Integer[]{1,2,7,3,5};
    Comparator<Integer> comp = new Comparator<Integer>() {
      public int compare(Integer d1, Integer d2) {
        return d1.compareTo(d2);
      }
    };
    MergeSorter.sort(values, comp);
    for (int i = 0; i < values.length; i++){
      System.out.print(values[i]+" ");
    }
    
  }
}

class MergeSorter {

  public static <E> void sort(E[] a, Comparator<? super E> comp) {
    mergeSort(a, 0, a.length - 1, comp);
  }


  private static <E> void mergeSort(E[] a, int from, int to, Comparator<? super E> comp) {
    if (from == to)
      return;
    int mid = (from + to2;
    // Sort the first and the second half
    mergeSort(a, from, mid, comp);
    mergeSort(a, mid + 1, to, comp);
    merge(a, from, mid, to, comp);
  }

  private static <E> void merge(E[] a, int from, int mid, int to, Comparator<? super E> comp) {
    int n = to - from 1;
    Object[] values = new Object[n];

    int fromValue = from;

    int middleValue = mid + 1;

    int index = 0;

    while (fromValue <= mid && middleValue <= to) {
      if (comp.compare(a[fromValue], a[middleValue]) 0) {
        values[index= a[fromValue];
        fromValue++;
      else {
        values[index= a[middleValue];
        middleValue++;
      }
      index++;
    }

    while (fromValue <= mid) {
      values[index= a[fromValue];
      fromValue++;
      index++;
    }
    while (middleValue <= to) {
      values[index= a[middleValue];
      middleValue++;
      index++;
    }

    for (index = 0; index < n; index++)
      a[from + index(Evalues[index];
  }
}
9.53.Sort
9.53.1.Bubble Sort
9.53.2.Selection Sort
9.53.3.Insertion Sort
9.53.4.Sorting Objects using insertion sort
9.53.5.Mergesort: merging two arrays into a third
9.53.6.Generic Merge Sorter with generic Comparator
9.53.7.Shellsort
9.53.8.Quicksort: simple version of quick sort
9.53.9.Quick sort with median-of-three partitioning
9.53.10.Quick sort: uses an insertion sort to handle subarrays of fewer than 10 cells
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.