package com.smppw.utils;

import java.util.List;
import java.util.Objects;

public class BinarySearchUtil {

    /**
     *
     * @param dateList   从小到大的净值序列
     * @param date  日期
     * @return  小于等于 date 的 日期最大的净值
     */
    public static Integer getMostLeftLessNav(List<String> dateList, String date) {
        if (dateList == null || dateList.size() == 0) {
            return 0;
        }
        int L = 0;
        int R = dateList.size() - 1;
        int ans = -1;
        while (L <= R) {
            int mid = (L + R) / 2;
            if (dateList.get(mid) !=null && dateList.get(mid).compareTo(date) <= 0) {
                ans = mid;
                L = mid + 1;
            } else {
                R = mid - 1;
            }
        }
        return ans == -1 ? 0 : ans;
    }

    /**
     *
     * @param dateList   从小到大的净值序列
     * @param date  日期
     * @return  小于 date 的 日期最大的净值
     */
    public static Integer getMostLeftLessNotEqualsNav(List<String> dateList, String date) {
        if (dateList == null || dateList.size() == 0) {
            return 0;
        }
        int L = 0;
        int R = dateList.size() - 1;
        int ans = -1;
        while (L <= R) {
            int mid = (L + R) / 2;
            if (dateList.get(mid) !=null && dateList.get(mid).compareTo(date) < 0) {
                ans = mid;
                L = mid + 1;
            } else {
                R = mid - 1;
            }
        }
        return ans == -1 ? 0 : ans;
    }


    /**
     *
     * @param dateList   从小到大的净值序列
     * @param date  日期
     * @return  大于等于 date 的 日期最小的净值
     */
    public static Integer getMostRightThanNav(List<String> dateList, String date) {
        if(dateList == null && Objects.requireNonNull(dateList).size() == 0){
            return -1;
        }else if(dateList.get(dateList.size()-1).compareTo(date) < 0){
            return dateList.size() - 1;
        }
        int low = 0;
        int high = dateList.size() - 1;
        while(low < high){
            //防止溢出
            int mid = low + (high-low)/2;
            if(dateList.get(mid).compareTo(date) < 0){
                low = mid + 1;
            }else{
                high = mid;
            }
        }
        return low;
    }

}
