given a two-dimensional array, sort the two-dimensional array in column I (i starts with 1), and if column I is the same, sort the same rows bythe elements of column I +1, if I +1 The elements of the column are the same, continue to compare the first +2 columns, and so on until the last column. If column I is the same as the last column, it is sorted in the original order.
Implement the following interfaces:
Enter an array of m*n integers, which are arranged by rules and return an array of permutations.
The caller will guarantee that:
For example, the input array is:
The
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: Start with a stable sorting algorithm from the last column (must be stable and can be sorted by bubbling sort), sorting to the specified columns.
The program code is as follows:
Function: Arrange an array of m rows n column Size//input: int * Parray Pointer to the first element of the array, M is the number of rows, n is the number of columns, please arrange/output by column I: The array sorted by column I is placed into the address specified in the input parameter (I value range 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];//start sorting from the last column, sorting to the specified column for (unsigned int column=n-1;column>=i-1;column-- ) {//Sort each column, bubble sort of deform for (unsigned int i=0;i<m-1;i++) {for (unsigned int j=0;j<m-i-1;j++) {//Interchange array element if (* (parray+j* N+column) > * (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;}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Column ordering for two-dimensional arrays