File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1- use std:: cmp:: { PartialEq , PartialOrd } ;
2-
3- pub fn binary_search < T : PartialEq + PartialOrd > ( item : & T , arr : & [ T ] ) -> Option < usize > {
4- if arr. is_empty ( ) {
5- return None ;
6- }
1+ use std:: cmp:: Ordering ;
72
3+ pub fn binary_search < T : Ord > ( item : & T , arr : & [ T ] ) -> Option < usize > {
84 let mut left = 0 ;
9- let mut right = arr. len ( ) - 1 ;
5+ let mut right = arr. len ( ) ;
106
117 while left < right {
12- let mid = left + ( right - left ) / 2 ;
8+ let mid = ( left + right) / 2 ;
139
14- if & arr[ mid] > item {
15- right = mid - 1 ;
16- } else if & arr[ mid] < item {
17- left = mid + 1 ;
18- } else {
19- left = mid;
20- break ;
10+ match item. cmp ( & arr[ mid] ) {
11+ Ordering :: Less => right = mid,
12+ Ordering :: Equal => return Some ( mid) ,
13+ Ordering :: Greater => left = mid + 1 ,
2114 }
2215 }
23-
24- if & arr[ left] == item {
25- Some ( left)
26- } else {
27- None
28- }
16+ None
2917}
3018
3119#[ cfg( test) ]
You can’t perform that action at this time.
0 commit comments