二分查找BinarySearch

07. November 2017 深度学习 0
php实现:
<?php
$arr = [1, 4, 3, 2, 7, 9, 33, 23, 6, 77, 44, 99, 12, 5, 6, 3, 1, 91];
function BinarySerch(int $key, array $arr): int
{
 $lo = 0;
 $hi = count($arr) - 1;
 while ($lo <= $hi) {
 $mid = $lo + intval(($hi - $lo) / 2);
 if ($key < $arr[$mid])
 $hi = $mid - 1;
 elseif ($key > $arr[$mid])
 $lo = $mid + 1;
 else
 return $mid;
 }
 return -1;
}

sort($arr);
$result = BinarySerch(23, $arr);
echo $result;
?>
JS实现
<script>
 var arr = [1, 4, 3, 2, 7, 9, 33, 23, 6, 77, 44, 99, 12, 5, 6, 3, 1, 91];
 arr.sort(function (a, b) {
 return a - b
 });
function BinarySearch(key) {
 var lo = 0;
 var hi = arr.length - 1;
 while (lo <= hi) {
 var mid = lo + parseInt((hi - lo) / 2);
 if (key < arr[mid]) {
 hi = mid - 1;
 } else if (key > arr[mid]) {
 lo = mid + 1;
 } else {
 return mid;
 }
 }
 return -1;
 }
document.write(BinarySearch(23));
</script>
Python实现
arr=[1, 4, 3, 2, 7, 9, 33, 23, 6, 77, 44, 99, 12, 5, 6, 3, 1, 91]
arr.sort()
def BinarySearch(key):
    lo=0
    hi=len(arr)-1
    while lo<=hi:
        mid = lo + (hi - lo) / 2
        if key<arr[mid]:
            hi=mid-1
        elif key>arr[mid]:
            lo=mid+1
        else:return mid
    return -1
print BinarySearch(23)
JAVA实现:
package lijian;
import java.util.Arrays;
public class BinarySearch {
public static int rank(int key, int[] arr) {
int lo = 0;
int hi = arr.length - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (key < arr[mid]) {
hi = mid - 1;
} else if (key > arr[mid]) {
lo = mid + 1;
} else {
return mid;
}
}
return -1;
}
public static void main(String[] args) {
int[] arr = { 1, 4, 3, 2, 7, 9, 33, 23, 6, 77, 44, 99, 12, 5, 6, 3, 1, 91 };
Arrays.sort(arr);
int result = rank(23, arr);
System.out.println(result);
}
}