Skip to content

Commit 8593330

Browse files
Sort modification
1 parent ef16e76 commit 8593330

File tree

2 files changed

+90
-0
lines changed

2 files changed

+90
-0
lines changed

Binary Search/Median of Array.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# https://www.interviewbit.com/problems/median-of-array/
2+
3+
# Median of Array
4+
5+
# There are two sorted arrays A and B of size m and n respectively.
6+
# Find the median of the two sorted arrays ( The median of the array formed by merging both the arrays ).
7+
# The overall run time complexity should be O(log (m+n)).
8+
9+
10+
def Med(A):
11+
mid = len(A)//2
12+
13+
if mid%2==0:
14+
return (A[mid-1]+A[mid])/2
15+
else:
16+
return A[mid]
17+
18+
19+
class Solution:
20+
# @param A : tuple of integers
21+
# @param B : tuple of integers
22+
# @return a double
23+
def findMedianSortedArrays(self, A, B):
24+
25+
A = list(A)
26+
B = list(B)
27+
28+
if len(A)==0 or len(B)==0:
29+
C = A+B
30+
if len(C) == 1:
31+
return C[0]
32+
else:
33+
return Med(C)
34+
35+
return (Med(A)+Med(B))/2
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# https://www.interviewbit.com/problems/rotated-sorted-array-search/
2+
3+
# Rotated Sorted Array Search
4+
5+
# Given an array of integers A of size N and an integer B.
6+
# array A is rotated at some pivot unknown to you beforehand.
7+
# You are given a target value B to search. If found in the array, return its index, otherwise return -1.
8+
# You may assume no duplicate exists in the array.
9+
10+
def BinarySearch(A,target):
11+
start = 0
12+
end = len(A) - 1
13+
14+
while(start<=end):
15+
mid = (start + end)//2
16+
if A[mid] == target:
17+
return mid
18+
elif A[mid]>target:
19+
end = mid -1
20+
else:
21+
start = mid + 1
22+
23+
return -1
24+
25+
def findMin(A):
26+
start = 0
27+
end = len(A)-1
28+
N = len(A)
29+
while(start<=end):
30+
if A[start]<=A[end]:
31+
return start
32+
mid = (start + end)//2
33+
nxt = (mid+1)%N
34+
prev = (mid-1+N)%N
35+
if A[mid]<=A[nxt] and A[mid]<=A[prev]:
36+
return mid
37+
elif A[mid]<=A[end]:
38+
end = mid -1
39+
elif A[mid]>=A[end]:
40+
start = mid +1
41+
42+
return -1
43+
44+
class Solution:
45+
# @param A : tuple of integers
46+
# @return an integer
47+
def search(self,A,B):
48+
A = list(A)
49+
n = findMin(A)
50+
if n == -1:
51+
return -1
52+
d
53+
54+
A.sort()
55+
return (BinarySearch(A,B)+n)%len(A)

0 commit comments

Comments
 (0)