Data Structures and Merge Sort Algorithms
Data Structures and Merge Sort Algorithms
Advertisements
Merge sort is a sorting technique based on divide and conquer technique. With worst-case time complexity being Οnlogn, it is one of the
most respected algorithms.
Merge sort first divides the array into equal halves and then combines them in a sorted manner.
We know that merge sort first divides the whole array iteratively into equal halves unless the atomic values are achieved. We see here
that an array of 8 items is divided into two arrays of size 4.
This does not change the sequence of appearance of items in the original. Now we divide these two arrays into halves.
We further divide these arrays and we achieve atomic value which can no more be divided.
Now, we combine them in exactly the same manner as they were broken down. Please note the color codes given to these lists.
We first compare the element for each list and then combine them into another list in a sorted manner. We see that 14 and 33 are in
sorted positions. We compare 27 and 10 and in the target list of 2 values we put 10 first, followed by 27. We change the order of 19 and
35 whereas 42 and 44 are placed sequentially.
In the next iteration of the combining phase, we compare lists of two data values, and merge them into a list of found data values placing
all in a sorted order.
After the final merging, the list should look like this −
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 1/2
10/11/2018 Data Structures and Merge Sort Algorithms
Algorithm
Merge sort keeps on dividing the list into equal halves until it can no more be divided. By definition, if it is only one element in the list, it
is sorted. Then, merge sort combines the smaller sorted lists keeping the new list sorted too.
Pseudocode
We shall now see the pseudocodes for merge sort functions. As our algorithms point out two main functions − divide & merge.
Merge sort works with recursion and we shall see our implementation in the same way.
l1 = mergesort( l1 )
l2 = mergesort( l2 )
var c as array
while ( a and b have elements )
if ( a[0] > b[0] )
add b[0] to the end of c
remove b[0] from b
else
add a[0] to the end of c
remove a[0] from a
end if
end while
return c
end procedure
To know about merge sort implementation in C programming language, please click here.
https://www.tutorialspoint.com/cgi-bin/printpage.cgi 2/2