Data Structure: How to implement Merge Sort in C++?
Merging is the process of combining two or more sorted files into a third sorted file. Merge sort is based on the divide and conquer paradigm. It can be explained as …. Let A[p…..r] is given array with indices p = 1 to r = n. Then steps can be
Image Source: https://en.wikipedia.org/wiki/Merge_sort
- Divide Step: If a given array A has zero or one element, then simply return; it is already sorted. Otherwise split A[p…..r] into two subarrays as A[p….q] and A[q+1…..r] each containing about the half of the elements.
- Conquer Step: Conquer by recursively sorted the two sub-arrays A[p….q] and A[q+1….r]
Source Code:
#includeusing namespace std; //create a class MergeSort class MergeSort{ public: int no_of_elements; int elements[10]; public: void getarray(); void partition(int [] ,int ,int); void sortit(int [], int , int, int); void display(); }; // get the array to be sorted from the user void MergeSort::getarray(){ cout>no_of_elements; cout>elements[i]; } } // recursively divide the array into sub arrays until all sub // arrays contain only one element void MergeSort::partition(int elements[], int low, int high){ int mid; if(low mid){ for(k=j;k
Output:
How many elements? 7
Insert element to sort: 63 78 52 12 99 32 13
The sorted element is
12 13 32 52 63 78 99
Efficiency of merge sort
Since the merge sort can not have more than logn passes and each pass involving ‘n’ or fewer comparisons, the merge sort requires no more than nlogn comparisons. Hence the efficiency of merge sort is O(nlogn).