Example 2: Sorting

The rows of a 10 x 3 matrix x are sorted in ascending order using Columns 0 and 1 as the keys. There are two missing values (NaNs) in the keys. The observations containing these values are moved to the end of the sorted array.

import com.imsl.math.*;
import com.imsl.stat.*;

public class SortEx2 {
    public static void main(String args[]) {
        
        int nKeys=2;
        double x[][] = {{1.0, 1.0, 1.0},
                        {2.0, 1.0, 2.0},
                        {1.0, 1.0, 3.0},
                        {1.0, 1.0, 4.0},
                        {2.0, 2.0, 5.0},
                        {1.0, 2.0, 6.0},
                        {1.0, 2.0, 7.0},
                        {1.0, 1.0, 8.0},
                        {2.0, 2.0, 9.0},
                        {1.0, 1.0, 9.0}};

        int iperm[]  = new int[x.length];
        x[4][1] = Double.NaN;
        x[6][0] = Double.NaN;
        
        PrintMatrix pm = new PrintMatrix("The Input Array");
        PrintMatrixFormat mf = new PrintMatrixFormat();
        mf.setNoRowLabels();
        mf.setNoColumnLabels();
        //	Print the array
        pm.print(mf, x);
        System.out.println(); 
        
        try {
        Sort.ascending(x, nKeys, iperm);
        } catch (Exception e) {
            
        }
        
        pm = new PrintMatrix("The Sorted Array - Lowest to Highest");
        mf = new PrintMatrixFormat();
        mf.setNoRowLabels();
        mf.setNoColumnLabels();
        
        //	Print the array
        pm.print(mf, x);
        
        pm = new PrintMatrix("The permutation array");
        mf = new PrintMatrixFormat(); 
        mf.setNoRowLabels();
        mf.setNoColumnLabels();  
        pm.print(mf, iperm);
    }
}


Output

The Input Array
           
1  1  1  
2  1  2  
1  1  3  
1  1  4  
2  ?  5  
1  2  6  
?  2  7  
1  1  8  
2  2  9  
1  1  9  


The Sorted Array - Lowest to Highest
           
1  1  1  
1  1  3  
1  1  4  
1  1  8  
1  1  9  
1  2  6  
2  1  2  
2  2  9  
2  ?  5  
?  2  7  

The permutation array
     
0  
2  
3  
7  
9  
5  
1  
8  
4  
6  

Link to Java source.