File tree 1 file changed +37
-0
lines changed
1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
1
+ # It returns location of x in given array arr
2
+ # if present, else returns -1
3
+ def binarySearch (arr , l , r , x ):
4
+
5
+ while l <= r :
6
+
7
+ mid = l + (r - l )/ 2 ;
8
+
9
+ # Check if x is present at mid
10
+ if arr [mid ] == x :
11
+ return mid
12
+
13
+ # If x is greater, ignore left half
14
+ elif arr [mid ] < x :
15
+ l = mid + 1
16
+
17
+ # If x is smaller, ignore right half
18
+ else :
19
+ r = mid - 1
20
+
21
+ # If we reach here, then the element was not present
22
+ return - 1
23
+
24
+ # Main Function
25
+ if __name__ == "__main__" :
26
+ # User input array
27
+ print ("Enter the array with comma separated in which element will be searched" )
28
+ arr = map (int ,input ().split ("," ))
29
+ x = int (input ("Enter the element you want to search in given array" ))
30
+
31
+ # Function call
32
+ result = binarySearch (arr , 0 , len (arr )- 1 , x )
33
+
34
+ if result != - 1 :
35
+ print ("Element is present at index {}" .format (result ))
36
+ else :
37
+ print ("Element is not present in array" )
You can’t perform that action at this time.
0 commit comments