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 floor(ArrayList<T> list, T key, Comparator<? super T> c) {
        if (c.compare(list.get(0), key) > 0) {
            return -1;
        }
        if (c.compare(list.get(list.size() - 1), key) <= 0) {
            return list.size() - 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(end), key);
        if (res > 0) {
            return start;
        } else {
            if (res == 0) {
                return end;
            } else {
                return -1;
            }
        }

    }

    public static <T> int floor(T[] array, T key, Comparator<? super T> c, int start, int end) {
        if (c.compare(array[start], key) > 0) {
            return -1;
        }
        end--;
        if (c.compare(array[end], key) <= 0) {
            return end;
        }
        int res;
        T mid;
        while (start < end - 1) {
            mid = array[(start + end) / 2];
            res = c.compare(mid, key);
            if (res > 0) {
                end = (start + end) / 2;
            } else {
                start = (start + end) / 2;
            }
        }
        res = c.compare(array[end], key);
        if (res > 0) {
            return start;
        } else {
            if (res == 0) {
                return end;
            } else {
                return -1;
            }
        }
    }
}