using
System;
class
GFG {
static
readonly
int
N = 4;
public
static
int
[] GetRow(
int
[, ] matrix,
int
row)
{
var
rowLength = matrix.GetLength(1);
var
rowVector =
new
int
[rowLength];
for
(
var
i = 0; i < rowLength; i++)
rowVector[i] = matrix[row, i];
return
rowVector;
}
static
void
mergeArrays(
int
[] arr1,
int
[] arr2,
int
N1,
int
N2,
int
[] arr3)
{
int
i = 0, j = 0, k = 0;
while
(i < N1 && j < N2) {
if
(arr1[i] < arr2[j])
arr3[k++] = arr1[i++];
else
arr3[k++] = arr2[j++];
}
while
(i < N1)
arr3[k++] = arr1[i++];
while
(j < N2)
arr3[k++] = arr2[j++];
}
static
void
printArray(
int
[] arr,
int
size)
{
for
(
int
i = 0; i < size; i++)
Console.Write(arr[i] +
" "
);
}
static
void
mergeKArrays(
int
[, ] arr,
int
i,
int
j,
int
[] output)
{
if
(i == j) {
for
(
int
p = 0; p < N; p++)
output[p] = arr[i, p];
return
;
}
if
(j - i == 1) {
mergeArrays(GetRow(arr, i), GetRow(arr, j), N,
N, output);
return
;
}
int
[] out1 =
new
int
[N * (((i + j) / 2) - i + 1)];
int
[] out2 =
new
int
[N * (j - ((i + j) / 2))];
mergeKArrays(arr, i, (i + j) / 2, out1);
mergeKArrays(arr, (i + j) / 2 + 1, j, out2);
mergeArrays(out1, out2, N * (((i + j) / 2) - i + 1),
N * (j - ((i + j) / 2)), output);
}
public
static
void
Main(String[] args)
{
int
[, ] arr = { { 2, 6, 12, 34 },
{ 1, 9, 20, 1000 },
{ 23, 34, 90, 2000 } };
int
K = arr.GetLength(0);
int
[] output =
new
int
[N * K];
mergeKArrays(arr, 0, 2, output);
Console.Write(
"Merged array is "
+
"\n"
);
printArray(output, N * K);
}
}