Beruflich Dokumente
Kultur Dokumente
Theory : Merge sort involves recursively splitting the array into 2 parts, sorting
and finally merging them. In 3-way merge sort 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.
Code :
package mergesort;
while ((i < mid1) && (j < mid2) && (k < high))
{
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))
{
if (gArray[i].compareTo(gArray[j]) < 0)
destArray[l++] = gArray[i++];
else
destArray[l++] = gArray[j++];
}
while ((j < mid2) && (k < high))
{
if (gArray[j].compareTo(gArray[k]) < 0)
destArray[l++] = gArray[j++];
else
destArray[l++] = gArray[k++];
}
while ((i < mid1) && (k < high))
{
if (gArray[i].compareTo(gArray[k]) < 0)
destArray[l++] = gArray[i++];
else
destArray[l++] = gArray[k++];
}
while (i < mid1)
destArray[l++] = gArray[i++];
Integer[] data = new Integer[] {45, -2, -45, 78, 30, -42, 10, 19, 73, 93};
mergeSort3Way(data);
Output :
Conclusion : In case of 3-way Merge sort we get the equation: T(n) = 3T(n/3) + O(n)
By solving it using Master method, we get its complexity as O(n log 3n). Although
time complexity looks less compared to 2 way merge sort, the time taken actually
may become higher because number of comparisons in merge function go higher.