public class BinarySearchUtils {
public static int binarySearch(int[]array
, int value
){
int start
= 0;
int end
= array
.length
-1;
while (true){
int mid
= (start
+ end
)/2;
int midValue
= array
[mid
];
if (value
== midValue
) {
return mid
;
} else {
if (midValue
> value
){
end
= mid
- 1;
} else {
start
= mid
+ 1;
}
}
if (start
> end
) {
return -1;
}
}
}
}
public class TestBinarySearchUtils {
public static void main(String
[] args
) {
int [] array
= {1,3,5,7,9};
int index1
= BinarySearchUtils
.binarySearch(array
, 7);
System
.out
.println(index1
);
}
}
import java
.util
.Arrays
;
public class Demo {
public static void main(String
[] args
) {
int [] arr
= {2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32};
int a
= Arrays
.binarySearch(arr
, 15);
int b
= Arrays
.binarySearch(arr
, 20);
int c
= Arrays
.binarySearch(arr
, 1,4,5);
int d
= Arrays
.binarySearch(arr
, 2,4,6);
int e
= Arrays
.binarySearch(arr
, 12,14,16);
int f
= Arrays
.binarySearch(arr
, 14,15,16);
int g
= Arrays
.binarySearch(arr
, 20,22,32);
System
.out
.println(a
);
System
.out
.println(b
);
System
.out
.println(c
);
System
.out
.println(d
);
System
.out
.println(e
);
System
.out
.println(f
);
System
.out
.println(g
);
}
}
转载请注明原文地址:https://tech.qufami.com/read-4083.html