|
1 | | -def binarysearch(arr,target): |
2 | | - low,high=0,len(arr)-1 |
3 | | - while low<=high: |
4 | | - mid=(low+high)//2 |
5 | | - if arr[mid]==target: |
| 1 | +def binarysearch(arr, target): |
| 2 | + low, high = 0, len(arr) - 1 |
| 3 | + while low <= high: |
| 4 | + mid = (low + high) // 2 |
| 5 | + if arr[mid] == target: |
6 | 6 | return mid |
7 | | - elif arr[mid]<target: |
8 | | - low=mid+1 |
| 7 | + elif arr[mid] < target: |
| 8 | + low = mid + 1 |
9 | 9 | else: |
10 | | - high=mid-1 |
| 10 | + high = mid - 1 |
11 | 11 | return -1 |
12 | 12 |
|
13 | 13 |
|
14 | | -arr=[int(x) for x in input("Enter the value: ").split(",")] |
15 | | -target=int(input("enter the target value: ")) |
16 | | -print(binarysearch(arr,target)) |
| 14 | +arr = [int(x) for x in input("Enter the value: ").split(",")] |
| 15 | +target = int(input("enter the target value: ")) |
| 16 | +print(binarysearch(arr, target)) |
17 | 17 |
|
18 | 18 |
|
19 | 19 | # Binary search |
20 | 20 |
|
21 | | -# Divide the search space into two halves by finding the middle index “mid”. |
22 | | -# Compare the middle element of the search space with the key. |
| 21 | +# Divide the search space into two halves by finding the middle index “mid”. |
| 22 | +# Compare the middle element of the search space with the key. |
23 | 23 | # If the key is found at middle element, the process is terminated. |
24 | 24 | # If the key is not found at middle element, choose which half will be used as the next search space. |
25 | 25 | # If the key is smaller than the middle element, then the left side is used for next search. |
@@ -71,7 +71,7 @@ def binarysearch(arr,target): |
71 | 71 | # else: |
72 | 72 | # print("Element is not present in array") |
73 | 73 |
|
74 | | -# Time Complexity: |
| 74 | +# Time Complexity: |
75 | 75 | # Best Case: O(1) |
76 | 76 | # Average Case: O(log N) |
77 | 77 | # Worst Case: O(log N) |
@@ -104,10 +104,7 @@ def binarysearch(arr,target): |
104 | 104 | # return -1 |
105 | 105 |
|
106 | 106 |
|
107 | | - |
108 | 107 | # arr=[int(x)for x in input('array').split(",")] |
109 | 108 | # v=int(input()) |
110 | 109 | # result=search(arr,0,len(arr),v) |
111 | 110 | # print(result) |
112 | | - |
113 | | - |
0 commit comments