diff --git a/rust/15_binary_search/binary_search.rs b/rust/15_binary_search/binary_search.rs new file mode 100644 index 0000000..cdbcad2 --- /dev/null +++ b/rust/15_binary_search/binary_search.rs @@ -0,0 +1,46 @@ +// 二分查找 +pub fn binary_search(nums: Vec, 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, value: i32) -> i32 { + if nums.is_empty() { return -1; } + + _recursion(&nums, 0, nums.len()-1, value) +} + +fn _recursion(nums: &Vec, 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)); +} diff --git a/rust/15_binary_search/sqrtx.rs b/rust/15_binary_search/sqrtx.rs new file mode 100644 index 0000000..fbfb6ac --- /dev/null +++ b/rust/15_binary_search/sqrtx.rs @@ -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)); +}