In a m*n matrix, each row is ordered in ascending order from left to right, and each column is sorted in ascending order from top to bottom. Complete a function to print the matrix into a one-dimensional array in order from small to large. , you should print out 1,2,2,4,4,6,7,8,8,9,9,10,11,12,13,15.
Ideas:
If you think of it as merging m arrays of size n, then the idea will be simple.
However, the matrix M and n are random values, so it is not easy to think of the kind of merging.
If we define an array of size m, his table corresponds to a different row of matrices,
The corresponding value we save the current matrix traversed to the position, because the different rows are sorted,
So we just need to find the smallest element in the M row, and put it in the specified array to sort it out.
For example:
For the first time, find the smallest 1 from 1 2 4 6, when the first element of the first line has been traversed, so we define the array s, corresponding to the S[0]+=1, representing the next traversal position at 1.
Code
int* Sort (intar[][4],intMintN) {int*ret = (int*)malloc(sizeof(int) *m*n);//array of saved results int*s = (int*)malloc(sizeof(int) *n);//Save current traverse position memset(S,0,sizeof(int) *n);//initialized to 0 for(intI=0; i < m*n; i++) {intmin=0;//Save minimum value in the first few lines while(S[min] = = n) min++;//If the current line is all over, you don't need to judge for(intL = min+1; L < m; l++) {if(Ar[min][s[min]] > Ar[l][s[l]) {min = l;//Update min location}} Ret[i] = Ar[min][s[min]];//Save Resultss[min]++;//Traverse location Update} Free(s);//Memory release returnRET;}
Run results
Sorting of matrices