|
1 | 1 | """ |
2 | | - Written By @searpheon - Arka |
3 | | - BINARY SEARCH |
| 2 | + Written By @searpheon - Arka |
| 3 | + Updated By @nishantcoder97 - Nishant Nahata |
| 4 | + BINARY SEARCH |
4 | 5 | """ |
5 | 6 |
|
6 | | -def binary_search(item_list,item): //creating the function |
7 | | - first = 0 //first element |
8 | | - last = len(item_list)-1 //self explanatory |
9 | | - found = False //setting value top false if we find the element we are looking for |
10 | | - while( first<=last and not found): |
11 | | - mid = (first + last)//setting value of middle element |
12 | | - if item_list[mid] == item : |
13 | | - found = True |
| 7 | +""" |
| 8 | + Condition: List should be sorted in ascending order |
| 9 | +""" |
| 10 | +def binary_search(item_list, item): |
| 11 | + """ |
| 12 | + param: list item_list: List to be searched |
| 13 | + param: int item: Item to be searched for |
| 14 | + returns: int index: Index of the first occurrence of item, or len(tem_list) if not found |
| 15 | + """ |
| 16 | + first = 0 |
| 17 | + last = len(item_list)-1 |
| 18 | + index = len(item_list) |
| 19 | + while first < last: |
| 20 | + mid = int((first + last) / 2) |
| 21 | + if item_list[mid] >= item: |
| 22 | + last = mid |
14 | 23 | else: |
15 | | - if item < item_list[mid]: |
16 | | - last = mid - 1 //shifting middle element's subset to the left |
17 | | - else: |
18 | | - first = mid + 1 //" " " " to the right |
19 | | - return found |
| 24 | + first = mid + 1 |
| 25 | + if item_list[first] == item: |
| 26 | + index = first |
| 27 | + return index |
| 28 | + |
| 29 | + |
| 30 | +if __name__ == '__main__': |
| 31 | + ### Tests ### |
| 32 | + print(binary_search([1,2,3,5,8], 6)) # returns len(item_list) |
| 33 | + print(binary_search([1,2,3,5,8], 5)) # returns 3 |
| 34 | + print(binary_search([1, 2, 3, 3, 3, 4, 4, 5, 10], 4)) # returns 5 |
| 35 | + |
20 | 36 |
|
21 | | -print(binary_search([1,2,3,5,8], 6)) |
22 | | -print(binary_search([1,2,3,5,8], 5)) |
|
0 commit comments