Sorting of matrices

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.