Skip to content

Commit c522a52

Browse files
committed
binary search
1 parent 90c7da0 commit c522a52

File tree

1 file changed

+63
-1
lines changed

1 file changed

+63
-1
lines changed

DSA/Binary_search.py

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,66 @@ def binarysearch(arr,target):
1313

1414
arr=[int(x) for x in input("Enter the value: ").split(",")]
1515
target=int(input("enter the target value: "))
16-
print(binarysearch(arr,target))
16+
print(binarysearch(arr,target))
17+
18+
19+
# Binary search
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.
23+
# If the key is found at middle element, the process is terminated.
24+
# If the key is not found at middle element, choose which half will be used as the next search space.
25+
# If the key is smaller than the middle element, then the left side is used for next search.
26+
# If the key is larger than the middle element, then the right side is used for next search.
27+
# This process is continued until the key is found or the total search space is exhausted.
28+
29+
# Python3 code to implement iterative Binary search
30+
# It returns location of x in given array arr
31+
32+
33+
# def binarySearch(arr, l, r, x):
34+
# while l<=r:
35+
# mid=l+(r-1)//2
36+
# if arr[mid]==x:
37+
# return mid
38+
# elif arr[mid]<x:
39+
# l=mid+1
40+
# else:
41+
# r=mid-1
42+
# return -1
43+
# # If we reach here, then the element
44+
# # was not present
45+
# arr = [int(i) for i in input('enter array: ').split(",")]
46+
# x = 10
47+
# result = binarySearch(arr, 0, len(arr)-1, x)
48+
# if result != -1:
49+
# print("Element is present at index", result)
50+
# else:
51+
# print("Element is not present in array")
52+
53+
54+
# Implementation of Recursive Binary Search Algorithm:
55+
56+
# def binary(arr,l,r,x):
57+
# if r>=l:
58+
# mid=l+(r-1)//2
59+
# if arr[mid]==x:
60+
# return mid
61+
# elif arr[mid]>x:
62+
# return binary(arr,l,mid-1,x)
63+
# else:
64+
# return binary(arr,mid+1,r,x)
65+
# return -1
66+
# arr = [int(i) for i in input('enter array: ').split(",")]
67+
# x = 10
68+
# result = binary(arr, 0, len(arr)-1, x)
69+
# if result != -1:
70+
# print("Element is present at index", result)
71+
# else:
72+
# print("Element is not present in array")
73+
74+
# Time Complexity:
75+
# Best Case: O(1)
76+
# Average Case: O(log N)
77+
# Worst Case: O(log N)
78+
# Auxiliary Space: O(1), If the recursive call stack is considered then the auxiliary space will be O(logN).

0 commit comments

Comments
 (0)