2

My teacher gave me a homework about how to Merge Sort two arrays in Pascal.

One of the arrays is named as N and sorted as ASCENDING..

Other array named as M and sorted as DESCENDING.

They are pre-defined and he wants me to Merge Sort these two arrays.

N [ 2, 4, 5, 8, 10 ]

M [ 9, 7, 6, 3, 1 ]

Merge Sort [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

So how can I do that?

Can anyone explain me this Merge Sort algorithm by simple coding examples?

Community
  • 1
  • 1
Berker Yüceer
  • 7,026
  • 18
  • 68
  • 102

1 Answers1

4

Your teacher is a clever guy, actually you need to understand what a mergesort does to merge two already sorted arrays. That's how mergesort works, it splits up the problem until there are two already sorted arrays, then it merges those arrays to one sorted array. This merging will be repeated until the whole array is sorted.

That's what you need to do (the code you should write on your own...)

  1. Create an array that is big enough to hold the elements of N and M

  2. For each position in the target array take the smallest remaining value of N and M. The smallest one you find like this:

    a. If there are no elements of N left, take the smallest element of M

    b. If there are no elements of M left, take the smallest element of N

    c. Otherwise compare the smallest elements of N and M and take the smaller one.

Because the arrays are already sorted, you know exactly at which position the smallest element of N and of M can be found.

Rohit Gupta
  • 4,022
  • 20
  • 31
  • 41
martinstoeckli
  • 23,430
  • 6
  • 56
  • 87