排序(2)-二分查找排序

原理:每一次都查中间的那个元素,比较大或者小就能减少一半的元素

前提:数组要有序

图解:

185140_VuOP_3735426.png

代码:

public class BinarySearchDemo {

	public static void main(String[] args) {

		// 定义一个有序数组
		int[] arr = {11, 22 , 33 , 44,55, 66, 77, 88, 99};
		int index = binarySearch(arr , 33);
		System.out.println(index);
	}
    /**
	 * 二分查找
	 * @param arr
	 * @param value
	 * @return
	 */
	public static int binarySearch(int[] arr , int value){

		// 定义三个变量
		int minIndex = 0 ;
		int maxIndex = arr.length - 1;
		int midIndex = (minIndex + maxIndex) / 2 ;
		// 循环
		while(minIndex <= maxIndex){
			if(arr[midIndex] == value){
				return midIndex ;
			}else if(arr[midIndex] > value){
				maxIndex = midIndex - 1 ;
			}else if(arr[midIndex] < value){
				minIndex = midIndex + 1 ;
			}

			midIndex = (minIndex + maxIndex) / 2 ;
		}

		return -1 ;
	}
}

代码优化方式一:

public class BinarySearchDemo {

	public static void main(String[] args) {

		// 定义一个有序数组
		int[] arr = {11, 22 , 33 , 44,55, 66, 77, 88, 99};
		int index = binarySearch2(arr , 33);
		System.out.println(index);
	}
    /**
	 * 优化后的代码
	 * @param arr
	 * @param value
	 * @return
	 */
	public static int binarySearch2(int[] arr , int value){

		// 定义三个变量
		int minIndex = 0 ;
		int maxIndex = arr.length - 1;
		// 循环
		while(minIndex <= maxIndex){
			int midIndex = (minIndex + maxIndex) / 2 ;

			if(arr[midIndex] == value){
				return midIndex ;
			}else if(arr[midIndex] > value){
				maxIndex = midIndex - 1 ;
			}else if(arr[midIndex] < value){
				minIndex = midIndex + 1 ;
			}
		}

		return -1 ;

	}

}

代码优化方式二:使用位移操作,左移一位,相当于除以2

public class BinarySearchDemo {

	public static void main(String[] args) {

		// 定义一个有序数组
		int[] arr = {11, 22 , 33 , 44,55, 66, 77, 88, 99};
		int index = binarySearch2(arr , 33);
		System.out.println(index);
	}
    /**
	 * 优化后的代码
	 * @param arr
	 * @param value
	 * @return
	 */
	public static int binarySearch2(int[] arr , int value){

		// 定义三个变量
		int minIndex = 0 ;
		int maxIndex = arr.length - 1;
		// 循环
		while(minIndex <= maxIndex){
			int midIndex = (minIndex + maxIndex) >> 1 ;

			if(arr[midIndex] == value){
				return midIndex ;
			}else if(arr[midIndex] > value){
				maxIndex = midIndex - 1 ;
			}else if(arr[midIndex] < value){
				minIndex = midIndex + 1 ;
			}
		}

		return -1 ;

	}

}

使用位运算的好处:更接近于计算机的底层,效率更高!

 

视频地址链接:

        原理:链接:https://pan.baidu.com/s/1i508PQt 密码:n7wg

       代码讲解链接:链接:https://pan.baidu.com/s/1slLrrMd 密码:40cr

转载于:https://my.oschina.net/u/3735426/blog/1586560

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值