jeudi 27 mai 2010

Merge two sorted array

Question is:

Let's say that we have two arrays A[1...n] and B[1...2n]:
- the first n elements of both arrays are sorted in ascending order
- the last n elements of B are empty

can you write some pseudo code to put all elements in a globally sorted order?


Solution:
General idea: start from the end of the array

i = n-1
j = i
k = 2n - 1
while ( k )
if i == 0
B[k--] = A[j]
j--
elsif j == 0
B[k--] = B[i]
i--
elsif (B[i] < A[j])
B[k--] = A[j]
j--
elsif A[j] =< B[i]
B[k--] = B[i]
i--

Aucun commentaire:

Enregistrer un commentaire