Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.util.ArrayList;
import java.util.Comparator;

public class Main {
    public static <T> int ceil(ArrayList<T> list, T key, Comparator<? super T> c) {
        if (c.compare(list.get(0), key) >= 0) {
            return 0;
        }
        if (c.compare(list.get(list.size() - 1), key) < 0) {
            return -1;
        }
        int start = 0, end = list.size() - 1, res;
        T mid;
        while (start < end - 1) {
            mid = list.get((start + end) / 2);
            res = c.compare(mid, key);
            //            System.out.println("res = " + res);
            //            System.out.println("mid = " + mid);
            if (res >= 0) {
                end = (start + end) / 2;
            } else {
                start = (start + end) / 2;
            }
            //            System.out.println("start = " + start);
            //            System.out.println("end = "+ end);
        }
        res = c.compare(list.get(start), key);
        if (res < 0) {
            return end;
        } else {
            if (res == 0) {
                return start;
            } else {
                return -1;
            }
        }

    }

    /**
     * 
     * @param <T>
     * @param array
     * @param key
     * @param c
     * @param start inclusive
     * @param end exclusive
     * @return 
     */
    public static <T> int ceil(T[] array, T key, Comparator<? super T> c, int start, int end) {
        if (c.compare(array[start], key) >= 0) {
            return start;
        }
        end--;
        if (c.compare(array[end], key) < 0) {
            return -1;
        }
        int res;
        T mid;
        while (start < end - 1) {
            mid = array[(start + end) / 2];
            res = c.compare(mid, key);
            //            System.out.println("res = " + res);
            //            System.out.println("mid = " + mid);
            if (res >= 0) {
                end = (start + end) / 2;
            } else {
                start = (start + end) / 2;
            }
            //            System.out.println("start = " + start);
            //            System.out.println("end = "+ end);
        }
        res = c.compare(array[start], key);
        if (res < 0) {
            return end;
        } else {
            if (res == 0) {
                return start;
            } else {
                return -1;
            }
        }
    }
}