Get a value for n the size of the list Get values for A A A
Solution
Please find my algorithm.Please let me know in case of any issue.
def median(A, length)
//odd length array
if length % 2 == 1 then
return quickselect(0, length-1, length/2)
else
lower = quickselect(0, length-1, length/2-1)
higher = quickselect(0, length-1, length/2)
return (lower + higher) / 2.0
end
end
# returns kth smallest element
def quickselect(A, left, right, k):
if left == right
return A[left]
pivot = (right+1 + left) / 2
new_pivot_index = partition(A, left, right, pivot)
diff = (new_pivot_index - left)
if diff == k
return A[new_pivot_index]
else if k < diff # kth element is in lower partition
return quickselect(A, left, new_pivot_index-1, k)
else # kth element is in higher partition
return quickselect(A, new_pivot_index+1, right, k-diff-1)
end
end
end
def partition(A, left, right, pivot)
pivot_value = A[pivot]
swap(pivot, right)
store_index = left
(left...right).each do |i|
if A[i] < pivot_value
swap(i, store_index)
store_index += 1
end
end
swap(store_index, right)
return store_index
end
def swap(A, from, to)
tmp = A[to]
A[to] = A[from]
A[from] = tmp
end

