Java List Merge merge(List left, List right)

Here you can find the source of merge(List left, List right)

Description

Helper method for the #mergeSort(List) method.

License

Open Source License

Parameter

Parameter Description
left List to be merged.
right List to be merged.

Return

The two given lists merged into one list.

Declaration

private static <E extends Comparable<? super E>> List<E> merge(List<E> left, List<E> right) 

Method Source Code

//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;
    }
}

Related

  1. merge(final List a, final List b)
  2. merge(final List aList, final List bList)
  3. merge(final String[] input, final String[] list)
  4. merge(List original, List merger)
  5. merge(List bs)
  6. merge(List list1, List list2)
  7. merge(List> list)
  8. merge(List l1, List l2)
  9. merge(List l1, List l2)