美文网首页
二分查找

二分查找

作者: 激扬飞雪 | 来源:发表于2019-06-25 11:31 被阅读0次
    package com.data.cn;
    
    import com.sun.org.apache.regexp.internal.RE;
    
    /**
     * Created by kaily on 17/5/9.
     */
    
    public class ArrayList {
        private final static int ARRAY_MAX_LENGTH = 10;
        private int array[];
        private int num;
    
        public ArrayList() {
            array = new int[ARRAY_MAX_LENGTH];
        }
    
        public int find(int value) {
    
            for (int i = 0; i < num; i++) {
                if (array[i] == value) {
                    return i;
                }
            }
            return -1;
        }
    
        public int findByOrder(int value) {
            int down = 0;
            int up = num;
            while (true) {
                int curI = (down + up) / 2;
                if (down > up) {
                    return num;
                }
                if (array[curI] == value) {
                    return curI;
                } else if (array[curI] < value) {
                    down = curI + 1;
                } else {
                    up = curI - 1;
                }
            }
    
        }
    
        public int delete(int value) {
            int index = find(value);
            if (index == -1) {
                return index;
            } else {
                for (int i = index; i < num; i++) {
                    array[i] = array[i + 1];
                }
                num--;
            }
            return index;
        }
    
        public int addByOrder(int value) {
            if (num == ARRAY_MAX_LENGTH) {
                return -1;
            }
    
            int index = 0;
            boolean isSearch = false;
            for (int i = 0; i < num; i++) {
                if (array[i] > value) {
                    index = i;
                    isSearch = true;
                    break;
                }
            }
    
            if (isSearch) {
                for (int i = num; i > index; i--) {
                    array[i] = array[i - 1];
                }
                array[index] = value;
            } else {
                array[num] = value;
            }
    
    
            num++;
            return num - 1;
        }
    
        public int add(int value) {
            if (num == ARRAY_MAX_LENGTH) {
                return -1;
            }
            array[num] = value;
            num++;
            return num - 1;
        }
    
        public int get(int index) {
            if (index >= num) {
                return -1;
            }
    
            return array[index];
        }
    
        public int size() {
            return num;
        }
    }
    

    相关文章

      网友评论

          本文标题:二分查找

          本文链接:https://www.haomeiwen.com/subject/wmttcctx.html