8000 Merge pull request #6 from suraj-goel/search · UN997/python@b80a3e6 · GitHub
[go: up one dir, main page]

Skip to content

Commit b80a3e6

Browse files
authored
Merge pull request AllAlgorithms#6 from suraj-goel/search
Adding search algos in python
2 parents 8ecadcb + ab73fce commit b80a3e6

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

search/binarySearch.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
2+
# Python Program for recursive binary search.
3+
4+
# Returns index of x in arr if present, else -1
5+
def binarySearch (arr, l, r, x):
6+
7+
# Check base case
8+
if r >= l:
9+
10+
mid = l + (r - l)/2
11+
12+
# If element is present at the middle itself
13+
if arr[mid] == x:
14+
return mid
15+
16+
# If element is smaller than mid, then it
17+
# can only be present in left subarray
18+
elif arr[mid] > x:
19+
return binarySearch(arr, l, mid-1, x)
20+
21+
# Else the element can only be present
< 8000 /td>22+
# in right subarray
23+
else:
24+
return binarySearch(arr, mid+1, r, x)
25+
26+
else:
27+
# Element is not present in the array
28+
return -1
29+
30+
# Test array
31+
arr = [ 2, 3, 4, 10, 40 ]
32+
x = 10
33+
34+
# Function call
35+
result = binarySearch(arr, 0, len(arr)-1, x)
36+
37+
if result != -1:
38+
print "Element is present at index %d" % result
39+
else:
40+
print "Element is not present in array"

search/linear.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
2+
# Python code for linearly search x in arr[]. If x
3+
# is present then return its location, otherwise
4+
# return -1
5+
def search(arr, x):
6+
7+
for i in range(len(arr)):
8+
9+
if arr[i] == x:
10+
return i
11+
12+
return -1

0 commit comments

Comments
 (0)
0