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

二分法查找和冒泡排序

//二分法查找    
public static void main(String[] args) {
        
        boolean found = false;
        Scanner sc = new Scanner(System.in);
        int zhong = sc.nextInt();//输入要找的数
        
        int [] a = new int []{1,7,11,15,18,21,23,25,31,35};//有序数组
        
        int low=0,high=9,mid=0;//下标
        while(low<=high){
            mid=(low+high)/2;//求中间下标
            //找到mid=zhong
            if(a[mid] == zhong){
                found = true;
                break;
            }
            else {
                if(a[mid]<zhong)
                {
                    low=mid+1;
                }
                else {
                    high=high-1;
                }
            }
        }
        //循环结束found的情况
        if(found == false){
            System.out.println("没找到");
        }
        else {
            System.out.println("找到了");
        }    
     }    
  }    
技术分享技术分享

public static void main(String[] args) {
        
        //冒泡排序
        int[] a = new int[]{24,5,48,45,64,57,52,74,88,91};
        //外层是趟数循环
        for(int i=1;i<=a.length-1;i++){
        //里层是次数循环
            for(int j=1;j<=a.length-i;j++){
        //把小的换到前面位置
                if(a[j]<a[j-1]){
                int kong = a[j];
                a[j]=a[j-1];
                a[j-1]=    kong;    
                }    
            }    
        }    
        //输出
        for(int i=0;i<=a.length-1;i++){
            System.out.print(a[i]+"\t");
                }
    }
}
技术分享
冒泡排序 从小到大输出。

 

 

 

二分法查找和冒泡排序