feat(geektime_algo): add 15 binary search

This commit is contained in:
Caitlin Gao 2019-07-16 10:52:21 +08:00
parent 250dc46020
commit 0968b1c17b
2 changed files with 74 additions and 0 deletions

View File

@ -0,0 +1,46 @@
// 二分查找
pub fn binary_search(nums: Vec<i32>, value: i32) -> i32 {
if nums.is_empty() { return -1; }
let mut low = 0;
let mut high = nums.len() - 1;
while low <= high {
let mid = low + ((high - low) >> 1);
if nums[mid] == value { return mid as i32; }
if nums[mid] < value {
low = mid + 1;
} else {
high = mid -1;
}
}
-1
}
// 二分查找递归
pub fn binary_search_recursion(nums: Vec<i32>, value: i32) -> i32 {
if nums.is_empty() { return -1; }
_recursion(&nums, 0, nums.len()-1, value)
}
fn _recursion(nums: &Vec<i32>, low: usize, high: usize, value: i32) -> i32 {
if low > high { return -1; }
let mid = low + ((high - low) >> 1);
if nums[mid] == value { return mid as i32; }
if nums[mid] < value {
return _recursion(nums, mid+1, high, value);
} else {
return _recursion(nums, low, mid-1, value);
}
}
fn main() {
let nums1 = vec![8,11,19,23,27,33,45,55,67,98];
let nums2 = vec![8,11,19,23,27,33,45,55,67,98];
println!("{:?}", binary_search(nums1, 23));
println!("{:?}", binary_search_recursion(nums2, 23));
}

View File

@ -0,0 +1,28 @@
// leetcode: https://leetcode.com/problems/sqrtx/
pub fn my_sqrt(x: i32, precision: f32) -> f32 {
if x == 0 || x == 1 { return x as f32; }
let mut left = 0f32;
let mut right = x as f32;
let mut res = 0f32;
while left <= right {
let mid: f32 = (right - left) / 2.0 + left;
if (right - left).abs() < precision { return mid; }
if mid > x as f32 / mid {
right = mid;
} else {
left = mid;
}
res = mid
}
res
}
fn main() {
println!("{:?}", my_sqrt(8, 0.000001));
}