Here you can find the source of merge(List
Parameter | Description |
---|---|
left | List to be merged. |
right | List to be merged. |
private static <E extends Comparable<? super E>> List<E> merge(List<E> left, List<E> right)
//package com.java2s; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Main { /**//w w w . j ava 2 s.c o m * 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; } }