常见对象_二分查找使用的注意事项

package cn.itcast_04;

/*
 * 注意:当前做法是错误的。
 * 		因为数组本身是无序的的,所以这种情况的查找是不能使用二分查找的。
 * 虽然你先排序了,但是你排序的时候已经改变了我最原始的元素索引。 
 */
public class ArrayDemo2 {
	public static void main(String[] args) {
		// 定义一个数组
		int[] arr = { 24, 69, 80, 57, 13 };

		// 选排序
		bubbleSort(arr);

		// 后查找
		int index = getIndex(arr, 80);
		System.out.println("index:" + index);

	}

	// 二分查找
	public static int getIndex(int[] arr, int value) {
		int max = arr.length - 1;
		int min = 0;

		int mid = (max + min) / 2;

		while (arr[mid] != value) {
			if (arr[mid] > value) {
				max = mid - 1;
			} else if (arr[mid] < value) {
				min = mid + 1;
			}

			mid = (max + min) / 2;
		}

		return mid;
	}

	// 冒泡排序
	private static void bubbleSort(int[] arr) {
		for (int x = 0; x < arr.length - 1; x++) {
			for (int y = 0; y < arr.length - 1 - x; y++) {
				if (arr[y] > arr[y + 1]) {
					int temp = arr[y];
					arr[y] = arr[y + 1];
					arr[y + 1] = temp;
				}
			}
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值