#include <iostream>
using namespace std;
struct Node {
int val;
int r;
int c;
};
void minHeapify(Node harr[], int i, int heap_size)
{
int l = i * 2 + 1;
int r = i * 2 + 2;
if(l < heap_size&& r<heap_size && harr[l].val < harr[i].val && harr[r].val < harr[i].val){
Node temp=harr[r];
harr[r]=harr[i];
harr[i]=harr[l];
harr[l]=temp;
minHeapify(harr ,l,heap_size);
minHeapify(harr ,r,heap_size);
}
if (l < heap_size && harr[l].val < harr[i].val){
Node temp=harr[i];
harr[i]=harr[l];
harr[l]=temp;
minHeapify(harr ,l,heap_size);
}
}
void sortedform(int mat[][3], int n)
{
int arr[n*n];
/*if row size 3 and column size 3 then the array should store 3*3=9 elements*/
Node harr[n];
for (int i = 0; i < n; i++)
harr[i] = { mat[0][i], 0, i };
Node p;
for (int i = 0; i <=n*n-1; i++) {
p = harr[0];
int nextval = (p.r < (n - 1)) ? mat[p.r + 1][p.c]: INT_MAX;
harr[0] = { nextval, (p.r)+1 ,p.c};
minHeapify(harr, 0, n);
arr[i]=harr[0].val;
}
for(int i=0;i<n*n;i++)
{
cout<<arr[i]<<" ";
}
}
// driver program to test above function
int main()
{
int mat[3][3]={ {1,5,7},{8,10,12},{14,16,17}};
sortedform(mat, 3);
return 0;
}
Comments
Post a Comment