Two-parameter array sorting

I have a 14x14 array, with each element being binary-packed information that, when unpacked, will give me two parameters: A and B. (Put parameters here in the form A: B for an easier discussion). Now I need to sort the array so that A grows from top to bottom (column) and B grows from left to right (row).

I thought about sorting the rows by B and then sorting the columns by A, but then I realized that this would not work. Let's say I sort the rows by B. Then when I sort the columns by A, this can ruin the order of B.

Any ideas?

+4
source share
1 answer

You can sort the entire list of 196 items by A, and then lay out the items so that the first line contains the smallest 14 A, the next line contains the next smallest, etc. Thus, each element of the i th row is smaller (according to A) than each element of the j row if i > j .

Then we go line by line and sort by B.

As a small example, let's make a 3x3 case with pairs (9.1) (8.2) ... (1.9). The variety in A will give (1.9) ... (9.1), which you will lay out as follows:

 (1,9) (2,8) (3,7) (4,6) (5,5) (6,4) (7,3) (8,2) (9,1) 

Then you sort each row by B. Reordering the elements of B does not violate the kernel's assumptions about A, because each element in this row is smaller than each element in the higher rows (for example, minimum A in the third row is 7, and maximum A second line - 6).

Then you will get:

 (3,7) (2,8) (1,9) (6,4) (5,5) (4,6) (9,1) (8,2) (7,3) 

EDIT: The question has been clarified as follows:

Well, it starts to make sense, but I’ll say that I have it: [[-1 -1 2: 8 -1 -1] [-1 3: 7 4:16 5: 2 -1] [2: 14 3 : 9 2: 6 5: 9 1: 2] [-1 9: 8 4: 2 9: 1 -1] [-1 -1 2: 2 -1 -1]]. "-1" represents a null value, so it should not be sorted. The final sorted array should remain in that diamond shape.

To maintain the “diamond shape”, you simply fill in the matrix as shown. Example:

 [[-1 -1 2:8 -1 -1] [ -1 3:7 4:16 5:2 -1] [ 2:14 3:9 2:6 5:9 1:2] [ -1 9:8 4:2 9:1 -1] [-1 -1 2:2 -1 -1]] 

Pull out the elements first

 [2:8 3:7 4:16 5:2 2:14 3:9 2:6 5:9 1:2 9:8 4:2 9:1 2:2] 

Then sort by A (In this case, to break the connection, we use the value of B):

 [1:2 2:2 2:6 2:8 2:14 3:7 3:9 4:2 4:16 5:2 5:9 9:1 9:8] 

Then build the necessary lines. If you look at the pattern, the number of elements in the rows is 1,3,5,3,1 , so the rows

 [[1:2] [2:2 2:6 2:8] [2:14 3:7 3:9 4:2 4:16] [5:2 5:9 9:1] [9:8]] 

Now we sort the rows by the value of B :

 [[1:2] [2:2 2:6 2:8] [4:2 3:7 3:9 2:14 4:16] [9:1 5:2 5:9] [9:8]] 

Now we can restore the diamond:

 [[-1 -1 1:2 -1 -1] [-1 2:2 2:6 2:8 -1] [4:2 3:7 3:9 2:14 4:16] [-1 9:1 5:2 5:9 -1] [-1 -1 9:8 -1 -1]] 

Make sure the rows and columns are sorted correctly :)

+5
source

Source: https://habr.com/ru/post/1486513/


All Articles