0% found this document useful (0 votes)
10 views4 pages

Merge Sort Algorithm Implementation

This document contains code to implement the merge sort algorithm. It includes functions for merging sorted subarrays, recursively applying the merge sort on subarrays, and a main function to test it on user input data. The merge sort algorithm divides the array into halves, recursively sorts the halves, and then merges the sorted halves back together.

Uploaded by

ethan bella meem
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views4 pages

Merge Sort Algorithm Implementation

This document contains code to implement the merge sort algorithm. It includes functions for merging sorted subarrays, recursively applying the merge sort on subarrays, and a main function to test it on user input data. The merge sort algorithm divides the array into halves, recursively sorts the halves, and then merges the sorted halves back together.

Uploaded by

ethan bella meem
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Merge Sort Code

#include <iostream>

using namespace std;

int Merge(int A[], int p, int q, int r)


{
int n1 = q-p+1;
int n2 = r-q;

int L[n1+1];
int R[n2+1];

for(int i=0; i<n1; i++)


{
L[i]=A[p+i];
}

for(int j=0; j<n2; j++)


{
R[j]=A[q+j+1];
}

L[n1]= 70000;
R[n2]= 80000;

int i = 0;
int j = 0;

3|Page
for(int k=p; k<=r; k++)
{
if(L[i]<=R[j])
{
A[k]=L[i];
i=i+1;
}
else
{
A[k]=R[j];
j=j+1;
}
}

int MergeSort(int Ar[], int P, int R)


{
int Q;
if(P<R)
{
Q = (P+R)/2;
MergeSort(Ar, P, Q);
MergeSort(Ar, Q+1, R);
Merge(Ar, P, Q, R);

}
}

4|Page
int main()
{
int size;
cout << "provide the length of the array: " << endl;
cin >> size;
cout << "the length is: " << size << endl;

int arr[size];
cout << "provide the input sequence of the array: " << endl;
for(int x = 0; x<size; x++)
{
cin >> arr[x];
}

MergeSort(arr, 0, size-1);

cout << "the output sequence of the array is: " << endl;
for(int y = 0; y<size; y++)
{
cout << arr[y]<<" ";
}
return 0;
}

Common questions

Powered by AI

The sentinel values 70000 and 80000 in the Merge Sort code are used to act as end markers for the auxiliary arrays L and R. These values ensure that the remaining elements from the other array can be copied over seamlessly once one of the arrays is exhausted. The numbers are chosen such that they are larger than any possible element in the original arrays to prevent them from incorrectly being considered during comparisons .

The structure of the MergeSort function involves the recursive division of the array and the use of auxiliary arrays L and R for merging. This recursive approach, coupled with auxiliary arrays, impacts space complexity as it requires additional memory allocation proportional to the input size n, leading to a space complexity of O(n). This may increase resource usage compared to iterative methods or in-place sorts. However, its predictable resource usage and stability make it suitable for sorting data where in-place sorting could lead to data corruption or where stability is essential .

If the base condition 'P < R' is not met, the MergeSort function infers that the array segment cannot be further divided, as it either represents a single element or an invalid segment. This condition is necessary to prevent infinite recursion by providing a clear stopping point for sub-array division. Without this condition, the function would attempt to repeatedly divide already minimal or non-existent segments, leading to execution errors or stack overflow .

In the merge function, the indices 'i' and 'j' track the current element of the left (L) and right (R) auxiliary arrays being considered for merging, respectively. The index 'k' tracks the position in the original array A where the next smallest element should be placed. By incrementing i or j based on element comparisons and advancing k with each placement, the function orderly merges the arrays segment by segment into the sorted order .

The provided code for the Merge Sort algorithm showcases its adaptability by allowing the dynamic input of array size and array elements directly from the user. This flexibility is crucial for applying the algorithm to various data sizes without requiring pre-compiled data structures or hardcoding. This adaptability is further enhanced by the algorithm's consistent O(n log n) time complexity, ensuring efficient operation even as input data sizes scale up .

The merge function contributes to the overall time complexity efficiency of the Merge Sort algorithm by sorting and combining two halves in linear time, O(n), relative to the number of elements being merged. Each level of recursion handles the merging of two n/2 element halves, and as recursions divide the array logarithmically (log n), the merge function’s linear merging ensures that each level combines outputs in a manner that maintains the overall time complexity of O(n log n) for the entire algorithm .

In the merge step of the Merge Sort algorithm, two sorted sub-arrays are integrated into a single sorted array by using two auxiliary arrays L and R. Each auxiliary array is initialized with the values of the sub-arrays, followed by sentinel values (70000 for L and 80000 for R) that function as infinite end markers. Then, through a series of comparisons between the current elements of L and R, the smallest element is placed into the original array. This process continues with the indices of L and R (i and j) being incremented accordingly, ultimately merging the arrays from positions p to r .

The MergeSort algorithm in C++ handles user input by prompting the user to provide the length of the array and the elements to be sorted. This is accomplished through the standard input (cin), followed by storing the input values into an array. This input process is significant as it supports dynamic data input for testing various scenarios of the algorithm, allowing users to real-time assess the MergeSort's effectiveness on different data sets and sizes .

The MergeSort function maintains the stability of sort by consistently choosing elements from the left auxiliary array L over the right R when elements are equal. This ensures that elements with the same value retain the same relative order as they appeared in the input array, crucial for preserving the stability of the sort. Stability is important in sorting because it allows subsequent operations to rely on the original ordering of equal elements, which is particularly useful in multi-level sorting scenarios where stability in intermediate sorting processes is required .

The recursive nature of the Merge Sort function allows the array to be repeatedly divided into halves until each sub-array contains a single element, thus inherently sorted. The base condition of the recursion checks if the array portion P is less than R, guaranteeing division. After reaching the base condition, the sorted sub-arrays are merged back together using the Merge function, which ensures that each layer of recursion returns a sorted array segment. This approach ensures systematic tackling of each subset of elements, leading to a fully sorted array upon completion of the recursion .

You might also like