Here you can find the source of mergeSort(List
To sort a given <code>List</code> of values.<br> Sorting algorithm: <b><i>MergeSort</i></b>.<br> Operates: <b><i>Recursively</i></b>.<br> More information: <a href="http://en.wikipedia.org/wiki/Merge_sort">http://en.wikipedia.org/wiki/Merge_sort</a>
Parameter | Description |
---|---|
m | List to to be sorted. |
public static <E extends Comparable<? super E>> List<E> mergeSort(List<E> m)
//package com.java2s; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Main { /**/*from w ww .j a v a2 s.c o m*/ * To sort a given <code>List</code> of values.<br> * Sorting algorithm: <b><i>MergeSort</i></b>.<br> * Operates: <b><i>Recursively</i></b>.<br> * More information: <a href="http://en.wikipedia.org/wiki/Merge_sort">http://en.wikipedia.org/wiki/Merge_sort</a> * * @param m List to to be sorted. * * @return Given list, sorted. * * @see #merge(List, List) */ public static <E extends Comparable<? super E>> List<E> mergeSort(List<E> m) { // Nothing to sort, return as is if (m.size() <= 1) { return m; } // Find the middle of given list int middle = m.size() / 2; // Split given list into two other lists, List<E> left = m.subList(0, middle); List<E> right = m.subList(middle, m.size()); // Recursively mergesort each lists right = mergeSort(right); left = mergeSort(left); // Merge the two lists together List<E> result = merge(left, right); return result; } /** * Helper method for the {@link #mergeSort(List<E>)} method. Takes care of merging the * two given <code>List</code>'s in a way depending on their values according to the * sorting algorithm <b><i>MergeSort</i></b>. * * @param left List to be merged. * @param right List to be merged. * * @return The two given lists merged into one list. * * @see #mergeSort(List) */ private static <E extends Comparable<? super E>> List<E> merge(List<E> left, List<E> right) { List<E> result = new ArrayList<E>(); Iterator<E> it1 = left.iterator(); Iterator<E> it2 = right.iterator(); E x = it1.next(); E y = it2.next(); while (true) { if (x.compareTo(y) <= 0) { result.add(x); if (it1.hasNext()) { x = it1.next(); } else { result.add(y); while (it2.hasNext()) { result.add(it2.next()); } break; } } else { result.add(y); if (it2.hasNext()) { y = it2.next(); } else { result.add(x); while (it1.hasNext()) { result.add(it1.next()); } break; } } } return result; } }