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;
}
}
}
}
}
常见对象_二分查找使用的注意事项
最新推荐文章于 2023-08-01 07:45:00 发布