0% found this document useful (0 votes)
42 views8 pages

Java Merge Sort and 3-Way Variant

The document discusses merge sort and a variant called 3-way merge sort. It provides pseudocode to implement 3-way merge sort in Java. The algorithm recursively splits the array into thirds at each step instead of halves like regular merge sort. Example inputs and outputs are given to demonstrate it sorting integer arrays.

Uploaded by

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

Java Merge Sort and 3-Way Variant

The document discusses merge sort and a variant called 3-way merge sort. It provides pseudocode to implement 3-way merge sort in Java. The algorithm recursively splits the array into thirds at each step instead of halves like regular merge sort. Example inputs and outputs are given to demonstrate it sorting integer arrays.

Uploaded by

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

Module-2

3) Sort a given set of n integer elements using Merge Sort method and Compute its time complexity. Run
the program for varied values of n > 5000, and record the time taken to sort. Demonstrate using Java how
the divide and conquer method works along with its time complexity analysis: worst case, average case
and best case.
import [Link];
import [Link];

public class Mergesorts


{
public static void main(String[] args)
{
int a[]= new int[100000];

Scanner in = new Scanner([Link]);


long start, end;
[Link]("****** MERGE SORT PROGRAM *********");
[Link]("Enter the number of elements to be sorted");
int n = [Link]();
Random rand= new Random();
for(int i=0;i<n;i++)
a[i]=[Link](10000);

[Link]("Array elements to be sorted are : ");


for(int i=0; i<n; i++)
[Link](a[i]+" ");

start=[Link]();
mergesort(a,0,n-1);
end=[Link]();

[Link]("\nThe sorted elements are : ");


for(int i=0; i<n; i++)
[Link](a[i]+" ");

[Link]("\nThe time taken to sort is "+(end-start)+" ns");


double best = n*[Link](n);
double avg = best;
double worst = best;
[Link]("\nBest Case = "+[Link](best)+"\nAverage = "+[Link](avg)+"\nWorst =
"+[Link](worst));
[Link]("\n******** ********************** *******");
}

static void mergesort(int a[], int low, int high)


{
int mid;
if(low < high)
{
mid = (low+high)/2;
mergesort(a, low, mid);
mergesort(a, mid+1, high);
merge(a, low, mid, high);
}
}

static void merge(int a[], int low, int mid, int high)
{
int i, j, h, k, b[]= new int[100000];

h=low;
i=low;
j=mid+1;

while((h<=mid) && (j<=high))


{
if(a[h] < a[j])
{
b[i] = a[h];
h=h+1;
}
else
{
b[i]=a[j];
j=j+1;
}
i = i+1;
}

if(h > mid)


{
for(k=j; k<=high; k++)
{
b[i] = a[k];
i = i+1;
}
}
else
{
for(k=h; k<=mid; k++)
{
b[i] = a[k];
i = i+1;
}
}
for(k=low; k<= high; k++)
a[k] = b[k];

}
}

OUTPUT 1:********** MERGE SORT PROGRAM *********


Enter the number of elements to be sorted
5000
Array elements to be
sorted are :3189
1841
3160
8740

The sorted
elements are:3
4
5
6
7
11
20
…..
The time taken to sort is 1173776857 ns
******** ********************** *******
OUTPUT 2:
********** MERGE SORT PROGRAM*******
Enter the number of elements to be sorted
6000
Array elements to be sorted are :
2853
3407
8435
8882
3709

The sorted elements are :
0
0
1
1
1
….
The time taken to sort is 1256530873 ns
******** ********************** *******
Module-2 Write a Java program with following: Merge sort involves recursively splitting the array into 2
parts, sorting and finally merging them. A variant of merge sort is called 3-way merge sort where instead
of splitting the array into 2 parts we split it into 3 parts. Merge sort recursively breaks down the arrays to
subarrays of size half. Similarly, 3-way Merge sort breaks down the arrays to subarrays of size one third.
Input : 45, -2, -45, 78, 30, -42, 10,19,73,93
Output : -45, -42, -2, 10, 19, 30, 45, 73, 78, 93
Input : 23, -19
Output : -19, 23

import [Link].*;

public class Mergesort


{
public static void mergeSort3Way(Integer[] gArray)
{
// if array of size is zero returns null
if (gArray == null) return;

// creating duplicate of given array


Integer[] fArray = new Integer[[Link]];

// copying elements of given array into duplicate array


for (int i = 0; i < [Link]; i++)
fArray[i] = gArray[i];

// sort function
mergeSort3WayRec(fArray, 0, [Link], gArray);

// copy back elements of duplicate array to given array


for (int i = 0; i < [Link]; i++)
gArray[i] = fArray[i];
}

/* Performing the merge sort algorithm on the given array of values in the rangeof indices (low, high). */
public static void mergeSort3WayRec(Integer[] gArray,int low, int high, Integer[] destArray)
{
// If array size is 1 then do nothing
if (high - low < 2)
return;

// Splitting array into 3 parts


int mid1 = low + ((high - low) / 3);
int mid2 = low + 2 * ((high - low) / 3) + 1;

// Sorting 3 arrays recursively


mergeSort3WayRec(destArray, low, mid1, gArray);
mergeSort3WayRec(destArray, mid1, mid2, gArray);
mergeSort3WayRec(destArray, mid2, high, gArray);

// Merging the sorted arrays


merge(destArray, low, mid1, mid2, high, gArray);
}

/* Merge the sorted ranges (low, mid1), (mid1, mid2) and (mid2, high) */
public static void merge(Integer[] gArray, int low, int mid1, int mid2, int high,Integer[] destArray)
{
int i = low, j = mid1, k = mid2, l = low;

while ((i < mid1) && (j < mid2) && (k < high)) // choose smaller of the smallest in the three ranges
{
if (gArray[i].compareTo(gArray[j]) < 0)
{
if (gArray[i].compareTo(gArray[k]) < 0)
destArray[l++] = gArray[i++];

else
destArray[l++] = gArray[k++];
}
else
{
if (gArray[j].compareTo(gArray[k]) < 0)
destArray[l++] = gArray[j++];
else
destArray[l++] = gArray[k++];
}
}
while ((i < mid1) && (j < mid2)) // case where first and second ranges have remaining values
{
if (gArray[i].compareTo(gArray[j]) < 0)
destArray[l++] = gArray[i++];
else
destArray[l++] = gArray[j++];
}
while ((j < mid2) && (k < high)) // case where second and third ranges have remaining values
{
if (gArray[j].compareTo(gArray[k]) < 0)
destArray[l++] = gArray[j++];
else
destArray[l++] = gArray[k++];
}
while ((i < mid1) && (k < high)) // case where first and third ranges have remaining values
{
if (gArray[i].compareTo(gArray[k]) < 0)
destArray[l++] = gArray[i++];
else
destArray[l++] = gArray[k++];
}

while (i < mid1) // copy remaining values from the first range
destArray[l++] = gArray[i++];

while (j < mid2) // copy remaining values from the second range
destArray[l++] = gArray[j++];

while (k < high) // copy remaining values from the third range
destArray[l++] = gArray[k++];
}

public static void main(String args[])


{
Integer[] data = new Integer[] {45, -2, -45, 78,30, -42, 10, 19, 73, 93};
mergeSort3Way(data);

[Link]("After 3 way merge sort: ");


for (int i = 0; i < [Link]; i++)
[Link](data[i] + " ");
}
}

Output:

Common questions

Powered by AI

In the Merge Sort implementation, the algorithm checks the base case by verifying if the portion of the array being processed has at most one element, indicated by if (low < high) for the standard Merge Sort, and if (high - low < 2) for the 3-way merge sort. When these conditions are met, it indicates that the array is trivially sorted, and no further recursive splitting or merging is needed .

In the Merge Sort algorithm, auxiliary space is used to temporarily store elements during the merging process. This auxiliary space enables efficient merging by holding elements that are being compared and placed in sorted order from both partitions. As each recursive step of the merge sort requires such space, the space complexity is O(n), where n is the number of elements being sorted, accounting for the need to store additional elements outside the original array .

The recursive nature of Merge Sort, whether the standard or the 3-way variant, effectively breaks down a large dataset into manageable, smaller units. By recursively splitting an array, the sorting process is simplified as each subarray sorted individually involves fewer elements. This systematic breaking down reduces the complexity faced with sorting large datasets as smaller arrays are easier to handle and can be sorted in linear time relative to their size. Furthermore, recursive splitting combined with efficient merging contributes significantly to the time efficiency, maintaining the O(n log n) complexity across variations .

During a 3-way merge in merge sort, the arrays are split into three sorted segments. The merge operation then requires examining the smallest elements from these segments and selecting the smallest among the three, ensuring elements are merged in sorted order. This involves additional complexity compared to two-range merges, as it requires maintaining three active pointers and handling overlaps between any two of the three ranges. The significance is that it allows greater flexibility and reduces recursive depth, but requires careful management to ensure all elements are correctly placed .

In the standard Merge Sort, merging two halves involves initializing indices for the two partitions and an auxiliary array. The algorithm compares elements from the two partitions, copying the smaller element to the auxiliary array. Once one partition is exhausted, the remaining elements of the other partition are copied directly into the auxiliary array. Finally, the sorted elements from the auxiliary array are copied back to the original array, ensuring the two halves are merged in sorted order .

Using random inputs of size greater than 5000 increases the processing time needed to sort these inputs significantly. The performance observations showed that the time taken by Merge Sort increases along with the input size, as indicated by the run times of 1173776857 ns for 5000 elements and 1256530873 ns for 6000 elements, reflecting the O(n log n) complexity. Hence, larger random inputs exemplify the scalability of Merge Sort, and while it handles such inputs efficiently, the performance is proportional to input size and complexity .

The 3-way merge sort splits the array into three parts instead of two, applying the merge sort recursively on each part. This change potentially reduces the depth of recursion, as each recursive call deals with smaller subarrays (approximately one-third of the current array size). While this could theoretically improve performance by reducing recursion depth, the increased complexity of managing three-way merges often balances this out, resulting in similar performance metrics compared with the original two-way merge sort .

A computational benefit of 3-way merge sort is the potential reduction in recursive depth due to splitting arrays into three parts, which could lead to more balanced and faster top-level transitions. Drawbacks include increased complexity in managing and implementing three-way merges, as extra steps are required to handle three subdivisions and ensure sorted merges. While it remains a viable alternative, the theoretical benefits often require careful implementation to realize and may not always translate to practical performance gains over traditional methods .

The divide and conquer strategy in Merge Sort involves recursively splitting the array into two halves, sorting each half, and then merging the sorted halves back together. This method breaks down the problem into smaller subproblems that are easier to solve. The time complexities for Merge Sort are O(n log n) for the best, worst, and average cases, as each split involves a log n depth of recursive calls and each merge operation involves processing n elements .

Automating sorting and timing using a Java program allows for precise, repeatable performance analyses of Merge Sort across various input sizes and configurations. It enables easy collection of timing metrics, supports testing on large data sets without manual errors, and allows visualization of performance trends. By adjusting input sizes and analyzing time taken, researchers can empirically verify Merge Sort's theoretical O(n log n) time complexity, providing clear insights into how performance scales with input size .

You might also like