using
System;
using
System.Collections.Generic;
public
class
GFG {
public
static
List<
int
> merge(List<
int
> tape1,
List<
int
> tape2)
{
if
(tape2.Count == 0) {
return
tape1;
}
List<
int
> outputTape =
new
List<
int
>();
int
i = 0, j = 0;
while
(i < tape1.Count && j < tape2.Count) {
if
(tape1[i] < tape2[j]) {
outputTape.Add(tape1[i]);
i++;
}
else
{
outputTape.Add(tape2[j]);
j++;
}
}
outputTape.AddRange(
tape1.GetRange(i, tape1.Count - i));
outputTape.AddRange(
tape2.GetRange(j, tape2.Count - j));
return
outputTape;
}
public
static
List<
int
>
balancedMergeSort(List<
int
> data,
int
numTapes)
{
List<List<
int
> > tapes =
new
List<List<
int
> >();
for
(
int
i = 0; i < numTapes; i++)
tapes.Add(
new
List<
int
>());
for
(
int
i = 0; i < data.Count; i++) {
tapes[i % numTapes].Add(data[i]);
}
for
(
int
i = 0; i < numTapes; i++) {
tapes[i].Sort();
}
while
(tapes.Count > 1) {
List<List<
int
> > newTapes
=
new
List<List<
int
> >();
for
(
int
i = 0; i < tapes.Count; i += 2) {
List<
int
> tape1 = tapes[i];
List<
int
> tape2 = (i + 1 < tapes.Count)
? tapes[i + 1]
:
new
List<
int
>();
newTapes.Add(merge(tape1, tape2));
}
tapes = newTapes;
}
return
tapes[0];
}
static
public
void
Main()
{
List<
int
> data =
new
List<
int
>{ 5, 2, 4, 6, 1, 3 };
List<
int
> sortedData = balancedMergeSort(data, 3);
for
(
int
i = 0; i < sortedData.Count; i++) {
Console.Write(sortedData[i] +
" "
);
}
Console.WriteLine();
}
}