冒泡排序,选择排序,二分法

public class Paixu {
    public static void main(String[] args) {
        int[]arr={1,2,8,10,18,22,28,100,20};
/*        //选择排序  从小到大
        for (int i = 0; i < arr.length-1; i++) {
            for (int j = i+1; j < arr.length; j++) {
                if (arr[i]>arr[j]) {
                    int tmp=arr[i];
                    arr[i]=arr[j];
                    arr[j]=tmp;
                }
            }
        }*/
        
        //冒泡排序 从小到大
    for (int i = 0; i < arr.length; i++) {
        for (int j = 0; j < arr.length-i-1; j++) {
            if (arr[j]>arr[j+1]) {
                int tmp=arr[j];
                arr[j]=arr[j+1];
                arr[j+1]=tmp;
                
            }
        }
    }    
    
        System.out.println(Arrays.toString(arr));
        //二分法
        
        System.out.println(search(arr, 20));
    }
    public static int search(int[]arr,int key){
        int start=0;
        int end=arr.length-1;
        while(arr[start]<=arr[end]){
            int middle=(end+start)/2;
            if (key<arr[middle]) {
                end=middle-1;
            }else if(key>arr[middle]){
                start=middle+1;
            }else{
                return middle;
            }
        }
        return -1;
        
    }
}

 

posted on 2016-12-23 00:01  放纵的卡尔  阅读(342)  评论(0编辑  收藏  举报

导航