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 ;}}