Column sorting of two-dimensional arrays

Source: Internet
Author: User

Column sorting of two-dimensional arrays

A two-dimensional array is provided. Sort the two-dimensional array by column I (I starts from 1). If column I is the same, the same row is ordered by the elements in column I + 1. If the elements in column I + 1 are the same, the column I + 2 will be compared, and so on, until the last column. If column I and the last column are the same, they are arranged in the original order.

 

Implement the following interfaces:

Enter an integer array of m * n to sort the data according to rules and return the sorted array.

The caller will ensure that:

For example, the input array is:

1, 2, 3

2, 3, 4

2, 3, 1

1, 3, 1

Sort by the second column:

Output:

1, 2, 3

2, 3, 1

1, 3, 1

2, 3, 4

 

Analysis: Use a stable Sorting Algorithm from the last column (must be stable, can use Bubble Sorting) to sort until the specified column.

The program code is as follows:

 

// Function: arrange an array of m rows and n columns. // input: int * pArray: pointer to the first element of the array. m indicates the number of rows, and n indicates the number of columns, sort by column I // output: Put the array after column I is sorted into the address specified by the input parameter (the value range of I is 1-n) // return: void RangeArray (int * pArray, unsigned int m, unsigned int n, unsigned int I) {if (pArray = NULL | m <0 | n <0 | I> n) return; int * tempArray = new int [n]; // sort from the last column to the specified column for (unsigned int column = n-1; column> = I-1; column --) {// sort each column, bubble sort deformation for (unsigned int I = 0; I
 
  
* (PArray + (j + 1) * n + column) {memcpy (tempArray, pArray + j * n, n * sizeof (int )); memcpy (pArray + j * n, pArray + (j + 1) * n, n * sizeof (int); memcpy (pArray + (j + 1) * n, tempArray, n * sizeof (int) ;}} if (column = 0) break ;}}
 


 

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.