算法读书笔记

需要注意的事项

1,在重写equals的时候要注意5点,自反性,对程序,传递性,一致性,非空性

查找

1,二分查找

public class BinarySearch {
    //二分查找,查找的数组必须有序
    public static int rank(int[] a,int key) {
        int lo = 0;
        int hi = a.length - 1;
        while(lo <= hi){
            int mid = lo + (hi - lo)/2;
            if (a[mid] > key) {
                hi = mid - 1;
            } else if (a[mid] < key ){
                lo = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }
}

二分查找递归写法

   //二分查找递归写法
    public static int rank2(int[] a,int key){
        return rank2(a,key,0,a.length - 1);
    }

    public static int rank2(int[] a,int key,int lo,int hi){
        if (lo > hi)
            return -1;
        int mid = lo + (hi - lo)/2;
        if (key > a[mid]){
            return rank2(a,key,mid + 1,hi);
        } else if (key < a[mid]){
            return rank2(a,key,lo,mid - 1);
        } else {
            return mid;
        }
    }

交换

1,将数组前后倒转

//数组前后倒转
    public static void exchangeArray(int[] a){
        int n = a.length;
        for (int i = 0; i < n/2; i++){
            int temp = a[i];
            a[i] = a[n - 1 -i];
            a[n - 1 -i] = temp;
        }
    }



你可能感兴趣的:(算法)