Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import java.util.*;

public class Main {
    /**
     * Unions the two given arrays in bag logic. The two arrays must be sorted and the union-elements will be added in
     * sorted order to the given collector.
     * 
     * @param collector
     *        is the {@link Collection} to which the unioned element will be written
     * @param a
     *        is the first union operand
     * @param b
     *        is the second union operand
     */
    public static <T extends Comparable<T>> void unionAll(final Collection<T> collector, final T[] a, final T[] b) {

        int index1 = 0;
        int index2 = 0;

        while (true) {
            if (index1 >= a.length) {
                copyRemainder(b, index2, collector);
                break;
            } else if (index2 >= b.length) {
                copyRemainder(a, index1, collector);
                break;
            } else {
                final T candidate1 = a[index1];
                final T candidate2 = b[index2];

                final int comparison = candidate1.compareTo(candidate2);

                if (comparison < 0) {
                    collector.add(candidate1);
                    index1++;
                } else if (comparison > 0) {
                    collector.add(candidate2);
                    index2++;
                } else {
                    collector.add(candidate2);
                    index1++;
                    index2++;
                }
            }
        }
    }

    /**
     * Adds all elements of the given array to the collector, starting from the given index.
     * 
     * @param sourceArray
     *        is the source array to copy from
     * @param startIndex
     *        is an index in the array from which the copying shall start
     * @param collector
     *        collects the copied elements
     */
    private static <T> void copyRemainder(final T[] sourceArray, final int startIndex,
            final Collection<T> collector) {

        for (int index = startIndex; index < sourceArray.length; index++) {
            collector.add(sourceArray[index]);
        }
    }
}