首页 > 代码库 > java 冒泡排序 二分查找

java 冒泡排序 二分查找

下面这个程序是先定义一个整型数组,然后将其中的元素反序赋值,再用冒泡排序进行排序以后用二分查找来查找其中是否有某个数,返回值为-1时表示这个数可能小于这个数组的最小值或大小这个数组的最大值,-2表示这个数比这个数组的最小值大,最大值小,但是数组中不包含这个数,代码如下:

package com.jll.sort;

public class ErFenSort {
    static int[] unsorted;
    public static void main(String[] args) {
        ErFenSort efs = new ErFenSort(10);
        buddleSort();
        for(int i=0;i<unsorted.length;i++){
            System.out.print(unsorted[i]+" ");
        }
        int index = search(2);
        System.out.println(index);
}
    public ErFenSort(int n) {
        unsorted = new int[n];
        for(int i=0;i<n;i++){
            unsorted[n-i-1] = i;
        }
    }
   
    public static int search(int index){
        int head=1;
        int tail=unsorted.length-1;
        int middle = 0;
        int turn = 0;
        while(head<=tail){
            middle = (tail+head)/2;
            if(index==unsorted[middle]){
                turn = middle+1;
                break;
            }else if(index < unsorted[middle]&&index >= unsorted[head]){
                tail = middle-1;
                continue;
            }else if(index>unsorted[middle]&&index<=unsorted[tail]){
                head = middle+1;
                continue;
            }else if(index<head||index>tail){
                turn = -1;
                break;
            }else{
                turn = -2;
                break;
            }
        }
        return turn;
    }
   
    public static void buddleSort(){
        for(int i=0;i<unsorted.length;i++){
            for(int j=0;j<unsorted.length-i-1;j++){
                if(unsorted[j]>unsorted[j+1]){
                    int temp = unsorted[j];
                    unsorted[j]=unsorted[j+1];
                    unsorted[j+1]=temp;
                }
            }
        }
    }
}

 

输出结果为:image_thumb