import java.util.Arrays;
/*
*已知int[] arr = {37, 92, 54, 18, 76};
*如何判断92是否存在?
*/
public class BinarySearch {
public static void main(String[] args) {
int[] arr = { 37, 92, 54, 18, 76 };
// 对数字排序
sort(arr);
// 输出排序后的字符串
System.out.println(Arrays.toString(arr));
// 二分法查找
System.out.println(search(arr, 37));
}
// 排序方法
public static void sort(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]) {
arr[y] = arr[y] ^ arr[y + 1];
arr[y + 1] = arr[y] ^ arr[y + 1];
arr[y] = arr[y] ^ arr[y + 1];
}
}
}
}
// 二分法查找方法
public static int search(int[] arr, int key) {
int start = 0;
int end = arr.length - 1;
int mid = (start + end) / 2;
while (arr[mid] != key) {
if (arr[mid] > key) {
end = mid - 1;
} else if (arr[mid] < key) {
start = mid + 1;
}
if (start > end) {
return -1;
}
mid = (start + end) / 2;
}
return mid;
}
/*public static int search(int[] arr, int key) {
// 定义开始、中间、结尾
int start = 0;
int end = arr.length - 1;
int mid = (start + end) / 2;
// key 与 arr[mid]比较
while (arr[mid] != key) {
if (arr[mid] > key) {
end = mid - 1;
} else if (arr[mid] < key) {
start = mid + 1;
}
if (start > end) {
return -1;
}
mid = (start + end) / 2;
}
return mid;
}*/
} |
|