快速排序和折半查找

package BinarySerach;

import java.util.Scanner;

public class BinarySerch {

	/**
	 *折半查找和快速排序
	 */
	static final int N = 15;
	static void quickSort(int [] array,int left,int right){
		int f,t;
		int ltemp =left;
		int rtemp = right;
		//确定分界值
		f = array[(left+right)/2];
		while(ltemp < rtemp){
			while(array[ltemp] <f){
				++ltemp;
			}
			while(array[rtemp] > f){
				--rtemp;
			}
			if(ltemp <= rtemp){
				t = array[ltemp];
				array[ltemp] = array[rtemp];
				array[rtemp] = t;
				--rtemp;
				++ltemp;
			}
			if(ltemp == rtemp){
				ltemp++;
			}
			
			if(left < rtemp){
				quickSort(array, left, ltemp-1);
			}
			if(ltemp < right){
				quickSort(array, 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));
		}
		for(i=0;i<N;i++){
			System.out.print("  "+shuzu[i]);
		}
		System.out.println("输出排序的结果:");
		quickSort(shuzu, 0, N-1);
		for(i=0;i<N;i++){
			System.out.print("  "+shuzu[i]);
		}
		System.out.println();
		System.out.println("输入要查找的数字");
		Scanner input = new Scanner(System.in);
		x = input.nextInt();
		n = searchFun(shuzu, N, x);
		System.out.println(n);
		if(n < 0){
			System.out.println("没有找到");
		}else{
			System.out.println("数据:"+x+"位于数组中的第"+(n+1)+"个元素处。");
		}
		
		
		
		

	}

}

  

转载于:https://www.cnblogs.com/aicpcode/p/4271366.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值