In the Merge Sort algorithm, we divide the array recursively in two halves until each sub-array contains a single element, & then we merge the sub-array in a way that results in a sorted array.

C++ Merge Sort

C++ Merge sort is an efficient & comparison-based algorithm lớn sort an array or a các mục of integers. Merge Sort keeps dividing the menu into equal halves until it can no more be divided.

By definition, it is sorted if there is only one element in the list. Then, Merge Sort combines the smaller sorted lists keeping the new list sorted. It is a Divide và Conquers algorithm which John von Neumann invented in 1945. Now you may question what is Divide và Conquer method is.


Merge sort in C++ first divides an array into equal halves and then combines them in a sorted manner. You can kiểm tra out Bubble Sort and Selection Sort examples in this blog.

Bạn đang xem: Merge sort — giải thuật lập trình

It is lượt thích the divide & conquer method. So let’s discuss the divide and concur method.


The divide và concur have the following three tasks.


Divide the problems into subproblems similar to lớn the original but smaller in size.Conquer the sub-problems recursively. If they are smaller in size, straightforwardly solve them.Combine those solutions lớn a solution, which is the answer lớn the original problem.

Let’s understand the merge sort in C++ và then write a program that demonstrates it.

How divide và conquer Algorithm works in Merge Sort

Sorting Problem: Sort a sequence of n elements into non-decreasing order.

Divide: Divide the n-element sequence lớn be sorted into two subsequences of n/2 elements each

Conquer: Sort the two subsequences recursively using merge sort.

Combine: Merge the two sorted subsequences to produce the sorted answer.

The top-down merge sort approach is a methodology that uses the recursion mechanism. It starts from the Top and proceeds downwards, with each recursive turn asking the same question such as “What is required khổng lồ be done to lớn sort the array?” and having an answer as, “split an array into two, make a recursive call, và merge the results.”, until one gets lớn the bottom of an array tree.

Example

Okay, now, before going to the code, first understand a model of Merge Sort; this will help you know the code.

Let us consider a các mục of integers:

43639324152721

 

So, as per the algorithm, we first need to lớn divide the length of the các mục (n) into two parts and so on until they are divided into one node.

So here, n=7 now n/2=3. Thus, the first part will of 3 integers, and the second part will be of 7-3=4 part.

Note that: If the kích cỡ of the list is even, then both sides will be divided equally. But for the case of ODD smaller kích cỡ will be on the left side, và the more significant will be on the right side.

So, after Step1, the list will be divided lượt thích the following.

43639324152721

 

Like this again, we will divide each of the lists by 2. The left side danh sách will be in 1+2, and the right side danh sách will appear in the 2+2 part. The same thing will happen again until they all get separated. So, here we will see the final các mục after the divide method. See the following figure.

*

Okay, after all the Divide operations are performed, we will perform Conquer, Sort the two subsequences recursively using merge Sort and Combine, that is, Merge the two sorted subsequences to lớn produce the sorted answer operation.

So here, we will see what will be the result after each step:

*

So, what happened here is… First, it compared two sub-sequences; for example, 63 và 93 are checked và then placed in ascending order after the merge. Similarly, 27 & 21 are checked and then placed ascending after merging.

Again in step two, 43,63,93 were checked & placed in ascending order after merge. In this way, we got our final shortlist.

15212427436393

Pseudo Code for Merge Sort

Merge Sort Pseudo Code is the following.

procedure mergesort( var a as array ) if ( n == 1 ) return a var l1 as array = a<0> ... A var l2 as array = a ... A l1 = mergesort( l1 ) l2 = mergesort( l2 ) return merge( l1, l2 )end procedureprocedure merge( var a as array, var b as array ) var c as array while ( a and b have elements ) if ( a<0> > b<0> ) showroom b<0> lớn the end of c remove b<0> from b else địa chỉ a<0> lớn the over of c remove a<0> from a kết thúc if kết thúc while while ( a has elements ) địa chỉ a<0> to the over of c remove a<0> from a over while while ( b has elements ) showroom b<0> to the end of c remove b<0> from b over while return cend procedure

C++ Merge Sort Program

See the following mergesort.cpp file.

#includeusing namespace std;int Merge(int A<>,int p, int q,int r) {int n1,n2,i,j,k; //size of left array=n1//size of right array=n2 n1=q-p+1;n2=r-q; int L,R;//initializing the value of Left part to lớn L<>for(i=0;i>n;int A,i;cout>A;//Calling the MergeSort()//First we are passing the array//the start index that is 0//and the form size of the array nMergeSort(A,0,n-1);coutThe output is the following.

*

Time Complexity for Merge Sort

Running time T(n) of Merge Sort:

Divide: computing the middle takes Θ(1)Conquer: solving 2 sub-problems takes 2T(n/2)Combine: merging n elements takes Θ(n)Total time complexity is the following.

T(n) = Θ(1) if n = 1T(n) = 2T(n/2) + Θ(n) if n > 1 T(n)= 2 T(n/2) + n = 2 ((n/2)log(n/2) + (n/2)) + n = n (log(n/2)) + 2n = n log n – n + 2n = n log n + n= O(n log n )The above recurrence can be solved either using the Recurrence Tree method or the Master method. It falls in case II of the Master Method, & the solution of the repetition is O(n log n).

The time complexity of the Merge Sort is O(n log n) in all 3 cases (worst, average, và best) as merge sort always divides the array into two halves & takes linear time to merge two halves.

With worst-case time complexity being Ο(n log n), it is one of the most respected algorithms.

Applications of Merge Sort

Merge Sort is useful for sorting linked lists in O(nLogn) time.It is used in Inversion Count Problem.We can use it in External Sorting.

Xem thêm: Hướng Dẫn Giải Phương Trình Bằng Phương Pháp Nhân Liên Hợp, Kỹ Thuật Liên Hợp Giải Phương Trình Chứa Căn

Conclusively, C++ Merge Sort Example is over.