Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*
 * Copyright (C) 2016 Timo Vesalainen <timo.vesalainen@iki.fi>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.Comparator;
import java.util.List;

public class Main {
    /**
     * Sort list using quick-sort algorithm
     * <p>Needs a big list to have any benefit to ArrayList.sort!
     * @param <T>
     * @param list
     * @param comparator 
     * @see java.util.ArrayList#sort(java.util.Comparator) 
     */
    public static final <T> void quickSort(List<T> list, Comparator<T> comparator) {
        quickSort(list, 0, list.size() - 1, comparator);
    }

    private static <T> void quickSort(List<T> list, int lo, int hi, Comparator<T> comparator) {
        if (lo < hi) {
            int p = partition(list, lo, hi, comparator);
            quickSort(list, lo, p, comparator);
            quickSort(list, p + 1, hi, comparator);
        }
    }

    private static <T> int partition(List<T> list, int lo, int hi, Comparator<T> comparator) {
        T pivot = list.get(lo);
        int i = lo - 1;
        int j = hi + 1;
        while (true) {
            do {
                i++;
            } while (compare(list.get(i), pivot, comparator) < 0);
            do {
                j--;
            } while (compare(list.get(j), pivot, comparator) > 0);
            if (i >= j) {
                return j;
            }
            T swap = list.get(i);
            list.set(i, list.get(j));
            list.set(j, swap);
        }
    }

    /**
     * If comp is not null compares using it. Otherwise assumes o1 is 
     * Comparable<T>.
     * @param <T>
     * @param o1
     * @param o2
     * @param comp
     * @return 
     */
    public static final <T> int compare(T o1, T o2, Comparator<T> comp) {
        if (comp != null) {
            return comp.compare(o1, o2);
        } else {
            return ((Comparable<T>) o1).compareTo(o2);
        }
    }
}