二分查找排序

static final int N=15;
	static void quickSort(int[] arr,int left,int right)			//快速排序算法
	{
	    int f,t;
		int rtemp,ltemp;

	    ltemp=left;
	    rtemp=right;
	    f=arr[(left+right)/2];						//确定分界值
		while(ltemp<rtemp){
	        while(arr[ltemp]<f) ++ltemp;
	        while(arr[rtemp]>f) --rtemp;
	        if(ltemp<=rtemp){                      //冒泡置换
				t=arr[ltemp];
		        arr[ltemp]=arr[rtemp];
	    	    arr[rtemp]=t;
				--rtemp;
	        	++ltemp;
			}
	    }
		
	    if(ltemp==rtemp) ltemp++;
	    if(left<rtemp)  quickSort(arr,left,ltemp-1);				//递归调用
	    if(ltemp<right) quickSort(arr,rtemp+1,right);				//递归调用
	}
	
	static int searchFun(int a[],int n,int x){                     //折半查找
	    int mid,low,high;
		low=0;
		high=n-1;
	    while(low<=high){
	   		mid=(low+high)/2;
			if(a[mid]==x)
	            return mid;						//找到
			else if(a[mid]>x)
			    high=mid-1;
	        else
				low=mid+1;
	    }
		return -1;								//未找到
	}
	
	public static void main(String[] args) {
		int[] shuzu=new int[N];
		int x,n,i;

		for(i=0;i<N;i++){
			shuzu[i]=(int)(100+Math.random()*(100+1));;				//产生数组
		}
		
		System.out.print("折半查找算法演示!\n");
	    System.out.print("排序前数据序列:\n");
	    for(i=0;i<N;i++)
		{
	        System.out.print(" "+shuzu[i]);					//输出序列
		}
		System.out.print("\n\n");
		quickSort(shuzu,0,N-1);				//排序
	    System.out.print("排序后数据序列:\n");
	    for(i=0;i<N;i++)
		{
	        System.out.print(" "+shuzu[i]);					//输出序列
		}
		System.out.print("\n\n");
	    System.out.print("输入要查找的数:");
	    Scanner input=new Scanner(System.in);
	    x=input.nextInt();							//输入要查找的数

	    n=searchFun(shuzu,N,x);						//查找

	    if(n<0)								//输出查找结果
           System.out.println("没找到数据:"+x);
		else
		   System.out.println("数据:"+x+" 位于数组的第"+(n+1)+" 个元素处。");
	}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

luozhonghua2000

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值