冒泡排序法,二分查找法

package com.hanqi;

public class maopaopaixu {

    public static void main(String[] args) {
        
        int[] a=new int[]{9,4,6,1,5,3,12,16,7,22,18,17,0,78,45};
        
        System.out.println("原始数据" );
        
        for(int t: a)
        {
            System.out.print(t+" ");
        }
        
        System.out.println(" ");
        
        for(int j=0;j<a.length;j++)
        {
            for(int i=0;i<a.length-1-j;i++)
            {
                if(a[i]>a[i+1])
                {
                    int b=a[i];
                    
                    a[i]=a[i+1];
                    
                    a[i+1]=b;            
                }          
            }
            
            System.out.print("第"+j+"次循环结果:");
            
            for(int t: a)
            {
                System.out.print(t+" ");                
            }
            System.out.println(" ");
            
        }
        System.out.print("最终排序结果:" );
        
        for(int t: a)
        {
            System.out.print(t+" ");                
        }
        System.out.println(" ");
    
    }

}
冒泡排序法

 

2、二分查找法

package com.hanqi;

import java.util.Scanner;

public class erfenchazhaofa {

    public static void main(String[] args) {
    
        int[] a=new int[]{1,2,3,4,5,6,7,8,9,10};
        
        System.out.println("请输入想要找到的数字(1-10):");
        
        Scanner sc=new Scanner(System.in);
        
        int m=sc.nextInt();
        
        int b=0;
        
        int d=9;
        
        int c=(b+d)/2;
        
        if(m>10||m<0)
          {
            System.out.println("输入的数字超过范围");
          }
        
        int sum=1;
        
        while(a[c]!=m)
        {
            if(a[c]>m)
            {
                d=c;
                
                c=(b+d)/2;
            
            }
            else
            {
                b=c;
                
                c=(b+d)/2;
            
            }
            sum+=1;
        }
        
        System.out.println("计算次数=" +sum);
        
        System.out.println("输入的"+m+"在第"+c+"位");
        
    }

}
二分查找法

 

posted @ 2016-02-29 16:55  1011042043  阅读(305)  评论(0编辑  收藏  举报