Unit-5 Merge Sort Algorithm
Unit-5 Merge Sort Algorithm
Merge sort is similar to the quick sort algorithm as it uses the divide and
conquer approach to sort the elements. It is one of the most popular and
efficient sorting algorithm. It divides the given list into two equal halves, calls
itself for the two halves and then merges the two sorted halves. We have to
define the merge() function to perform the merging.
The sub-lists are divided again and again into halves until the list cannot be
divided further. Then we combine the pair of one element lists into two-
element lists, sorting them in the process. The sorted two-element pairs is
merged into the four-element lists, and so on until we get the sorted list.
Keep Watching
Competitive questions on Structures in Hindi
00:00/03:34
Algorithm
In the following algorithm, arr is the given array, beg is the starting
element, and end is the last element of the array.
The important part of the merge sort is the MERGE function. This function
performs the merging of two sorted sub-arrays that are A[beg…
mid] and A[mid+1…end], to build one sorted array A[beg…end]. So, the
inputs of the MERGE function are A[], beg, mid, and end.
According to the merge sort, first divide the given array into two equal
halves. Merge sort keeps dividing the list into equal parts until it cannot be
further divided.
As there are eight elements in the given array, so it is divided into two arrays
of size 4.
Now, again divide these two arrays into halves. As they are of size 4, so
divide them into new arrays of size 2.
Now, again divide these arrays to get the atomic value that cannot be further
divided.
In combining, first compare the element of each array and then combine
them into another array in sorted order.
So, first compare 12 and 31, both are in sorted positions. Then compare 25
and 8, and in the list of two values, put 8 first followed by 25. Then compare
32 and 17, sort them and put 17 first followed by 32. After that, compare 40
and 42, and place them sequentially.
In the next iteration of combining, now compare the arrays with two data
values and merge them into an array of found values in sorted order.
Now, there is a final merging of the arrays. After the final merging of above
arrays, the array will look like -
Now, the array is completely sorted.
1. Time Complexity
2. Space Complexity
Space O(n
Complexity )
Stable YES