File tree Expand file tree Collapse file tree 1 file changed +11
-24
lines changed Expand file tree Collapse file tree 1 file changed +11
-24
lines changed Original file line number Diff line number Diff line change 11use std:: cmp:: Ordering ;
22
3- #[ allow ( dead_code) ]
4- fn binary_search < T > ( items : Vec < T > , value : T ) -> Option < usize >
3+ #[ warn ( dead_code) ]
4+ fn binary_search < T > ( list : Vec < T > , item : T ) -> Option < usize >
55where
66 T : std:: cmp:: Ord ,
77{
8- if items. is_empty ( ) {
9- // Avoid running if no items are provided
8+ if list. is_empty ( ) {
109 return None ;
11- }
12-
13- let ( mut start, mut end) = ( 0 , items. len ( ) - 1 ) ;
10+ } ;
11+ let ( mut low, mut high) = ( 0 , list. len ( ) - 1 ) ;
1412
15- loop {
16- let idx = ( start + end) / 2 ;
17- let attempt = items. get ( idx) . unwrap ( ) ;
18-
19- if start > end {
20- break ;
21- }
13+ while low <= high {
14+ let mid = ( low + high) / 2 ;
2215
23- match attempt. cmp ( & value) {
24- Ordering :: Greater => {
25- end = idx - 1 ;
26- }
27- Ordering :: Less => {
28- start = idx + 1 ;
29- }
30- Ordering :: Equal => {
31- return Some ( idx) ;
32- }
16+ match list[ mid] . cmp ( & item) {
17+ Ordering :: Greater => high = mid,
18+ Ordering :: Less => low = mid + 1 ,
19+ Ordering :: Equal => return Some ( mid) ,
3320 }
3421 }
3522
You can’t perform that action at this time.
0 commit comments