Page 1 of 1

Problem: Find the element that would be at the kth position in a combined sorted array. Given the two sorted arrays of s

Posted: Fri Jul 08, 2022 6:15 am
by answerhappygod
Problem:
Find the element that would be at the kth position in a combinedsorted array. Given the two sorted arrays of size m and nrespectively.
example:
Arr1 = [1,2,3,5,6] ; Arr2 = [3,4,5,6,7] ; K = 5
returns = 4
I have the code done but All the tests fail when adding:
def merge(arr, x, y, z): #It merges and sorts the divided arrayusing this merge function as the part of divide and conquerstrategy
l1 = y - x + 1
l2 = z- y
A = [0] * (l1)
B = [0] * (l2)
for i in range(0 , l1):
A = arr[x + i]
for j in range(0 , l2):
B[j] = arr[y + 1 + j]
i = 0
j = 0
k = x
while i < l1 and j < l2 :
if A <= B[j]:
arr[k] = A
i += 1
else:
arr[k] = B[j]
j += 1
k += 1
while i < l1:
arr[k] = A
i += 1
k += 1
while j < l2:
arr[k] = B[j]
j += 1
k += 1
def mergeSort(arr,x,z):
if x < z:
y = (x+(z-1))//2
mergeSort(arr, x, y) #it divides and sorts the first half
mergeSort(arr, y+1, z) #it divides and sorts the second half
merge(arr, x, y, z)
def kthElement(Arr1,Arr2,k):
Arr1+=Arr2 #Appending the both arrays...
n = len(Arr1) #storing the length of the array1
mergeSort(Arr1,0,n-1)
print ("\n\nSorted array is") #printing the sorted array..
for i in range(n):
print ("%d" %Arr1)
print("\nThe element at kth index is : %d"%Arr1[k]) #printingthe element at the specified index...
#driver code..
Arr1 = [1,2,3,5,6]
Arr2 = [3,4,5,6,7]
print("\nArr1")
print(Arr1)
print("\nArr2")
print(Arr2)
k = int(input("Enter the kth position of the Array : "))
kthElement(Arr1,Arr2,k-1)

Problem Find The Element That Would Be At The Kth Position In A Combined Sorted Array Given The Two Sorted Arrays Of S 1
Problem Find The Element That Would Be At The Kth Position In A Combined Sorted Array Given The Two Sorted Arrays Of S 1 (62.76 KiB) Viewed 32 times
What I'm missing here?
1) Test: No elements repeat in lists (0.0/1.0) Test Failed: 15 != None : Expected value: 15 Value from your code: None 2) Test: One or more elements repeat in one list (0.0/1.0) Test Failed: 11 != None : Expected value: 11 Value from your code: None 3) Test: One or more elements repeat in both list (0.0/1.0) Test Failed: 9 != None : Expected value: 9 Value from your code: None 4) Test: First list contains contains negative numbers (0.0/1.0) Test Failed: 32 != None : Expected value: 32 Value from your code: None 5) Test: Second list contains negative numbers (0.0/1.0) Test Failed: 10 != None : Expected value: 10 Value from your code: None 6) Test: Both lists together in sorted order (0.0/1.0) Test Failed: 13 != None : Expected value: 13. Value from your code: None Check submitted files (0.0/0.0) All required files submitted!