SAYAN-2000
/
Must-Do-Coding-Questions-For-Service-Based-Companies-and-Product-Based-Companies.
Public
forked from rohitjila/Must-Do-Coding-Questions-For-Service-Based-Companies-and-Product-Based-Companies.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMerge 2 sorted array without extra space
46 lines (37 loc) · 980 Bytes
/
Merge 2 sorted array without extra space
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
def nextGap(t):
if (t <= 1):
return 0
return (t//2) + (t%2)
def merge(arr1,arr2,n,m):
gap=n+m
gap=nextGap(gap)
while(gap > 0):
i=0
while(i+gap < n):
if(arr1[i] > arr1[i+gap]):
arr1[i],arr1[i+gap]=arr1[i+gap],arr1[i]
i+=1
j=gap-n if gap > n else 0
while(i < n and j < m):
if (arr1[i] > arr2[j]):
arr1[i],arr2[j]=arr2[j],arr1[i]
i+=1
j+=1
if (j < m):
j=0
while(j+gap < m):
if (arr2[j] > arr2[j+gap]):
arr2[j],arr2[j+gap]=arr2[j+gap],arr2[j]
j+=1
gap=nextGap(gap)
arr1=[1,4,7,8,9]
arr2=[2,3,9]
n=len(arr1)
m=len(arr2)
merge(arr1,arr2,n,m)
for i in range(n):
print(arr1[i],end=" ")
print()
for i in range(m):
print(arr2[i],end=" ")
print()