View Single Post
  #1   Report Post  
Posted to microsoft.public.excel.programming
Dave Ring Dave Ring is offline
external usenet poster
 
Posts: 20
Default Mergeing two Arrays

This will merge two sorted arrays of variant. If you want another data
type, just dimension A1 to A3 accordingly.

Dave Ring

Sub Merge(A1(), A2(), A3())
Dim I&, J&, K&, N1&, N2&, N3&

'merges sorted arrays A1 and A2 into A3
N1 = UBound(A1) + 1 'if array is 0 based
N2 = UBound(A2) + 1
N3 = N1 + N2
ReDim A3(0 To N3 - 1) 'again, 0 based
I = 0: J = 0: K = 0
Do
If A1(I) <= A2(J) Then
A3(K) = A1(I): I = I + 1: K = K + 1
If I = N1 Then 'A1 is used up, so
Do 'move the rest of A2
A3(K) = A1(J): J = J + 1: K = K + 1
Loop Until J = N2: Exit Do
End If
Else
A3(K) = A1(J): J = J + 1: K = K + 1
If J = N2 Then 'A2 is used up, so
Do 'move the rest of A1
A3(K) = A1(I): I = I + 1: K = K + 1
Loop Until I = N1: Exit Do
End If
End If
Loop
End Sub


Paul W Smith wrote:
Has anyone got any sample code for merging two sorted one dimensional arrays
into one sorted new one?

e.g.

A1 = (2, 4, 6, 8)
A2 = (2, 3, 4, 9, 10)

RESULT = (2, 3, 4, 6, 8, 9, 10)