public static void main(String[] args) {
int[] arr = {11,22,33,44,55,66,77};
System.out.println(PaiXu(arr, 44));
System.out.println(PaiXu(arr, 55));
System.out.println(PaiXu(arr, 22));
System.out.println(PaiXu(arr, 66));
System.out.println(PaiXu(arr, 88));
}
public static int PaiXu(int[]arr,int a){
// return Demo1(arr, a);
// return Demo2(arr, a);
int min =0;
int max=arr.length-1;
int mid=(min+max)/2;
while(arr[mid]!=a){
if (arr[mid]>a) {
max=mid-1;
}else if (arr[mid]<a) {
min=mid+1;
}
mid=(min+max)/2;
if (min>max) {
return -1;
}
}
return mid;
}
private static int Demo2(int[] arr, int a) {
int min=0;
int max=arr.length-1;
int mid=(max+min)/2;
while(arr[mid]!=a){
if (arr[mid] > a) {
max=mid-1;
}else if (arr[mid]<a) {
min=mid+1;
}
mid=(max+min)/2;
if (min>max) {
return -1;
}
}
return mid;
}
private static int Demo1(int[] arr, int a) {
int min=0;
int max=arr.length-1;
int mid=(max+min)/2;
while (arr[mid]!=a) {
if (arr[mid]>a) {
max=mid-1;
}else if (arr[mid]<a) {
min=mid+1;
}
mid=(max+min)/2;
if (min>max) {
return -1;
}
}
return mid;
}
}
|
|