How to sort a 2 dim Array ?

hello
I would like to sort a 2-dim array of double ( double[][])
according to the 1st column
It is possible to sort a 1st dim array (doubel[]) , but the method sort
of the class Array doesn't work with double[][]).
I have two (bad) solutions.
1) Writing a sorting method but I would prefer using the sort' method of java which uses quicksort
2) Creating a table of objects that implements Comparable but this would decrease performance
Do you have a better Idea ?
Thanks a lot

I would like to sort a 2-dim array of double (double[][]) according to the 1st column
Which is the first "column"? double[0][x] or
double[x][0]?
If it's the second one things get simple: your
double[][] is really an array of objects where each
object is an array of doubles. So all you need to do
is write a custom Comparator for double[] to use the
sort method:
compare(Object obj1, Object obj2) {
double[] d1 = (double[]) obj1;
double[] d2 = (double[]) obj2;
return d1[0] > d2[0];
}Thanks for your so prompt answer.
I can manage to put the data so that I sort the array according to x as in double[x][0]?
But WHERE do I have to write the "compare" method ?
Thanks

Similar Messages

  • How to sort a 2 dim. array by the first column?

    Hi there,
    I need to know, how to sort a 2 dim. String array by the first column, which means "string[0][x]".
    I think, I have to implement a new comparator class. But how?
    Thanks in advance for any help

    I need to know, how to sort a 2 dim. String
    array by the first column, which means
    "string[0][x]".You want to sort the array using the first element in each row and that element is a String?
    Let's forget about generics. Say you want to supply a Comparator. The compare method should decide the order between elements when passed two element objects. In a two-dimensional array the elements will be one-dimentional arrays and you use the first element in those arrays, like
    public int compare(Object s1, Object s2) {
       String[] a1 = (String[]) s1;  // first row array
       String[] a2 = (String[]) s2;  // second row array
       return a1[0].compareTo(a2[0]); // compare first element of row arrays
    }

  • Sort a 2-dim array?

    Hello!
    Now we have the following problem: We need to sort a 2-dim array depending on the values in the first column. Then we need the corresponding row to move to the right place too... we send a VI so you can see an example of how it might look like. So we need (in this case) the first column to sort so we get 1,2 and 3 and so on, so the last row should be 3,4, 392 and 2047.
    We think this might be easy to solve but we need some tip :-) Thank you and best regards.
    Attachments:
    sortarray.vi ‏17 KB

    I wrote my own 2D string array sort routine. It has come in handy many times. You can enter the column number that you want to sort on, and the entire rows are rearranged in the order of the column sort. If your array is numeric, you can easily change the vi to use numerics instead. One day I hope to make it polymorphic. Here it is:
    - tbob
    Inventor of the WORM Global
    Attachments:
    Sort2DArray(str).vi ‏63 KB

  • How do I find the total number of elements in a multi dim array

    How do I find the total number of elements in a single or multi dim array?
    For example, a 2x3 array has 6 elements, and a 2x3x4 has 24. How do I compute this very easily - is there a single VI that does this?
    David
    Solved!
    Go to Solution.

    Use "array size" (array palette) followed by "multiply array elements" (numeric palette)
    (Works also equally well for 3D arrays and higher)
    For a 1D array, just use "array size".
    Message Edited by altenbach on 02-05-2009 05:57 PM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    NumberOfElements.png ‏3 KB

  • In the attached vi, I have a 2-dim series of EMGs which I would like to connect with a 1-dim array. How can I do this?

    In the attached vi, de Y values are given for each time as a matrix. The problem is that the y values coming out have to be a 1-dim array, in order to connect this vi with another vi. How can I do this?
    Attachments:
    3-dim_Filter.vi ‏48 KB

    Hi,
    can you post your curve fitting .vi?
    I think you can do this with the reshape array.vi, and take the 2-D array, find out it's size, and multiply the two dimensions together to get the number of elements you need. That'll give you the array as 1-D, but whether it's in the correct order as you need it is another matter.
    It all depends on what the 2-D array is representing, and how much of it needs to go to the "other" .vi
    Hope that helps
    S.
    // it takes almost no time to rate an answer

  • How to declare an expandable 2-dim Array

    Hi,
    How do I declare a 2-dim array that is can expandable with additional data?

    Look at this example (Catching the ideas of the other guis:
    e.g. create a Class Object which represents a Row
    class Row {
    ArrayList list = new ArrayList(10); //ten columns
    public Object getObject(int x) {
    list.get(x);
    public void setObject(Object o, int x) {
    list.add(x, o);
    Create an Table Object which is able to add your Rows-Objects
    class Table {
    ArrayList rows = new ArrayList();
    public void addRow(Row row) {
    rows.add(row);
    public Row getRow(int x) {
    return (Row) rows.get(x);
    public int getNrOfRows() {
    return rows.size();
    after this, you can fill your Objects like this
    Row row = new Row();
    row.setObject(0, "James");
    row.setObject(1, "Kirk");
    row.setObject(2, "Captain);
    Table table = new Table():
    table.add(row);
    Hope it helps a little bit

  • How to fill up a 3-dim array?

    Hello!
    See the attached vi. We want to fill upp a 3-dim array. The pages are "number". If "true" is true then we want to insert the row that we build inside the case on page number "number". But the problem is that the new element is placed outside the 3-dim array because the pages are not the same size. How can this problem be solved? Maybe we should use "replace element" ? Does anyone have a tip or idea?
    Thank you and best regards.
    Attachments:
    trouble1.vi ‏51 KB

    Hello Ex-jobb,
    if you want to replace an element of an array, than the index has to be inside that array... Otherwise you have to add an element using build array.
    I changed your example a little bit.
    1) Adding a row with your "Replace Array element", but now using two index values. You may change the second index to your needs.
    2) Making the array constant "bigger" by setting a values at index [6,6,6]. You can NOT replace anything inside an empty array!
    Hope this helps,
    GerdW
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome
    Attachments:
    trouble1.vi ‏51 KB

  • Two dim array

    hello
    it would be really nice if someone could help me with that.
    i am trying to sort an array and i have read that i can do that with a statement called sort(), but it doesn't seem to work.
    this is what i have tried:
    for(int i = 0; i < arr.length; i++)
           for(int j = 0; j < arr.length; j++)
               sort(arr[i][j]);
    }the error i get is:
    Exercise5W2.java [56:1] No method found matching sort(int)
    sort(arr[i][j]);
    ^
    1 error
    thanks for ur help!

    You can use the java.util.Arrays.sort() with and without
    the java.util.Comparator interface.
    First you sort all individual one-dim int arrays,
    then you sort the whole two-dim array.
    Here is how it goes:
    // 2-dim int array example
    int[][] twoDimIntArray = { { 4, 67, 45 }, { 23, 98, 3}, { 2, 68, 112}, { 333, 5, 21 } };
    // First you sort all individual 1-dim int arrays
    for (int i = 0; i < twoDimIntArray.length; i++)
        Arrays.sort(twoDimIntArray);
    // Then you sort the whole 2-dim array (with an house made Comparator)
    Arrays.sort((Object[])twoDimIntArray, new TwoDimIntArrayComparator());
    // Print out the result
    for (int i = 0; i < twoDimIntArray.length; i++)
    for (int j = 0; j < twoDimIntArray[i].length; j++)
    System.out.print(twoDimIntArray[i][j] + " ");
    System.out.println();
    // Here is the Compararor for 2-dim int array objects
    class TwoDimIntArrayComparator implements Comparator
    public int compare(Object o1, Object o2)
    int[] oneDimIntArray1 = (int[])o1;
    int[] oneDimIntArray2 = (int[])o2;
    // First integer of each array to be different,
    // return the comparison
    for (int i = 0; i < oneDimIntArray1.length; i++)
    if (oneDimIntArray1[i] > oneDimIntArray2[i])
    return 1;
    else if (oneDimIntArray1[i] < oneDimIntArray2[i])
    return -1;
    // All integers of the arrays are equal
    return 0;
    public boolean equals(Object obj)
    return false;

  • How can I pass an empty array to a parameter of type PLSQLAssociativeArray

    How can I pass an empty array to a parameter of type PLSQLAssociativeArray in VB? I defined the parameter like this
    Dim myArray() as String = new String() {}
    Dim myPara as new Oracle.DataAccess.Client.OracleCollectionType.PLSQLAssociativeArray
    myPara = 0
    myPara.Value = myArray
    When I execute my stored procedure giving the above parameter, I got error saying OracleParameter.Value is invalid.
    I have tried to give it the DBNull.Value, but it doesn't work either.
    Note: everything works fine as long as myArray has some item in there. I just wonder how I can make it works in case I have nothing.
    Thank you,

    How can I pass an empty array to a parameter of type PLSQLAssociativeArray in VB? I defined the parameter like this
    Dim myArray() as String = new String() {}
    Dim myPara as new Oracle.DataAccess.Client.OracleCollectionType.PLSQLAssociativeArray
    myPara = 0
    myPara.Value = myArray
    When I execute my stored procedure giving the above parameter, I got error saying OracleParameter.Value is invalid.
    I have tried to give it the DBNull.Value, but it doesn't work either.
    Note: everything works fine as long as myArray has some item in there. I just wonder how I can make it works in case I have nothing.
    Thank you,

  • How to sort files by TimeStamp.

    Hello friends,
    I have files which has following format.
    Paymentxxxx.xml where xxxx is time in YYYYMMDDHH:MM:SS format.Example file name can be
    Payment20010726143455.xml.How to sort such files according to time so that i can get old files first.
    Thanks

    <pre>
    import java.util.*;
    import java.text.*;
    class Timing
         public static void main(String[] args)
              try
              SimpleDateFormat sdf=new SimpleDateFormat();
              String formatter="yyyyMMddhhmmss";
              sdf.applyPattern(formatter);
              //Accept files names here , and deduct extension and pass them into array as following
              String[] inputdates={"19760909132332","19760909032332","19830901132332","19800909132332"};
              Date[] conversionDate=new Date[inputdates.length];
              for(int i=0;i<inputdates.length;i++)
                   conversionDate=sdf.parse(inputdates[i]);
              Date[] outputDates=sortDates(conversionDate);//Sorting dates
              for(int i=0;i<outputDates.length;i++)
              System.out.println(outputDates[i]);//CONVERT DATES INTO STRINGS
              catch(Exception e)
         private static Date[] sortDates(Date[] dates)
              int COUNT = dates.length;
              int j;
              Date tempDate;
              for(int i=0;i<COUNT;i++)
                   j=i-1;
                   tempDate=dates[i];
                   while(j>=0 && tempDate.before(dates[j]))
                        dates[j+1]=dates[j];
                        dates[j]=tempDate;
                        j--;
              return dates;
    </pre>

  • System.arraycopy (2 dim array) and growth of 2 dim array

    Hi everybody
    I am working on a program which contains a module that can perform Cartesian product on number of sets.
    The code I have developed so far is :
    import java.lang.reflect.Array;
    public class Cart5 {
    public static void main(String[] args) throws Exception
    int pubnewlength;
    // declare SolArray
    int[][] solArray;
    // initialize solArray
    solArray=new int[1][4];
    // Use for method
    for (int ii=0 ; ii<4 ; ii++)
    solver(solArray,ii);
    // Print the array ?
    System.out.println("\n  The array was changed ... " );
    }  // End main
    public void solver(int Solarray2[][] , int abi)
    int[][]  A  =  {  {1,2,3,5},
                      {4,6,7},
                      {11,22,9,10},
                      {17,33}
      jointwoArrays(solarray2,A,abi);
    // some other operations
    } // End Solver method
    public void jointwoArrays(int solarray3[][] , int aArray[][],int indexA)
    int y,u;
    int[][] tempArray;
    // calculate growth of rows:
    pubnewlength=solArray3.length * aArray[indexA].length;
    //Fill TempArray
    y=solArray3[0].length;
    u=solArray3.length;
    tempArray=new int[u][y];
    // Use system.arraycopy to copy solArray3 into tempArray -- How ?
    // Change the size of arrow to proper size -- How ?
    solArray3 = (int[][]) arrayGrow(solArray3);
    // Join operation - Still under construction
    for(int i = 0, k = 0; i < tempArray.length; i++)
                   for(int j = 0; j < set3.length; j++)
                                     for (q=0;q<=2;q++)             
                                      { solArray3[k][q] = tempArray[i][q];}
                                     solArray3[k][q]= aArray[indexA][j];
                                     ++k;
    } // End jointwoArrays method
    // This module is from http://www.java2s.com/ExampleCode/Language-Basics/Growarray.htm
        static Object arrayGrow(Object a) {
        Class cl = a.getClass();
        if (!cl.isArray())
          return null;
        Class componentType = a.getClass().getComponentType();
        int length = Array.getLength(a);
        int newLength = pubnewlength;
        Object newArray = Array.newInstance(componentType, newLength);
        System.arraycopy(a, 0, newArray, 0, length);
        return newArray;
    } // End ClassI deeply appreciate your help with these 3 questions :
    1. How can I use system.arraycopy to copy my two dimensional array? I have searched but examples seem to be about one dim arrays.
    2. How can I change the "static Object arrayGrow(Object a)" , to grow my two dimensional array ?
    3. If you know any codes or articles or java code regarding cartesian products , please tell me.
    Thank you
    Denis

    1. How can I use system.arraycopy to copy my two
    dimensional array? I have searched but examples seem
    to be about one dim arrays.That's because you can't do it in one call. You need to create a loop which copies each 'row".
    >
    2. How can I change the "static Object
    arrayGrow(Object a)" , to grow my two dimensional
    array ?Why do you make it so complicated (generic). Make it take an int[][] array instead, and see the answer from above.
    >
    3. If you know any codes or articles or java code
    regarding cartesian products , please tell me.There are probably lots of them if you google.
    Kaj

  • Sorting a two dimensional array

    Hello!
    I have a twodimensional array that consists of 6 other arrays
    (like array[0 to 5][0 to 4]). The [4] of each sub-array is a index
    number that i'd like to use for sorting the array[0][x] to
    array[5][x] according to their array[x][4]-value. How would I do
    that?
    Thanks!

    use a custom sort function. check the sort() method of the
    array class for sample coding.

  • Create a 2-dim array dynamically

    Hello!
    I have had this problem here before but try one moore time :-)
    This is the thing: We have a text-file from which we read. This textfile can be different from time to time. From this textfile we can catch numbers of columns and numbers of rows that a 2-dim array should have. The problem is how one can create this 2-dim array dynamically? We have a while-loop that the program runs inside already. Must one use the while-loop to solve this problem? Or can one solve this with only a for-loop? Hope you understand how I mean :-) Best regards

    OK, I thought you want to read an array of the same size as the actual data in the file. You cannot read a 4x10 array if the file only contains data for a 3x5 array .
    Is the array size determined by the data in the file or by some other calculation?
    I would still read the entire file, then you can cut out a 2D subset using "array subset". This should not be a problem unless you have millions of array elements.
    LabVIEW Champion . Do more with less code and in less time .

  • Sorting a 2-D array

    Hello Every one,
                            Can any one please help me out in sorting a 2-D array. Here is the requirement there will be some groups, and each group consists of 'x' number of elements.The user enters only elements but in a zig zag order. And the program short sort out each channel and list out to which group it is belonging (Where the 2-D array of Group name and elements is provided).
    Say for example if there are three groups with some elements in each groups as follows.
    Physics: retarder, force,torque,capacity
    Chemistry: reaction, chemicals, sodium
    Geography: land,map,soil, earth.
    And if the user enters the following input's: soil, torque, chemical, force,reaction, land.
    The program should return the following output:
    Note : The order of the elements should match the order they are defined.
    Physics, force,torque                                    ------------ group name and group elements in the first row
    Chemistry, reaction, chemical                        ------------ group name and group elements in the Second row
    Geography,land, soil                                    ------------ group name and group elements in the third row
    Thanks for the help
    - Raghu
    Solved!
    Go to Solution.

    Sure Jim, I can definitely share my project details.Here is what we are trying to achieve.
    The attached vi is used to transmit the messages to Engine ECM. It takes the input's *.dbc file where the channel names are defined
    The present vi is working like this. It transmit messages correctly only if the messages are defined in the ascending order(the order in which they are defined in the *.dbc file).
    Say for example take 3 PGNS
    1) 18ff0fef Which has the following channels in the PGN
    a) Notch
    b) Gear
    c) Service brake
    2) 14ff2ef which has the following channels in the PGN
    a) Bus_voltage
    b) Bus_current
    c) power
    3)14ff03ef which has the following channels in the PGN
    a) Coolant_temp
    b) oil_press
    c) Imat
    If I want to transmit the following channels and define them in the following order
    1) Gear
    2) Imat
    3) Bus_voltage
    4) Notch
    The program is only writing correct data for Gear,Imat and some garbage values for Bus_voltage and Notch.
    But if I define the channels in the ascending order as defined in the *.dbc file in the following fashion
    1)Notch
    2)Gear
    3)Bus_voltage
    4)Imat
    I can transmit the right data for each channel.
    So what Iam trying to do is Iam planning to sort out all the channels names what user enter's and sort the channels in the  order as defined in the *.dbc file and pass it to the program.
    And the other issue I am facing is if two channels belong to the same PGN like Gear and Notch I have to transmit the values in the same array.
    Say for example i want to transmit the values as follows Notch =4; Gear = 3; Bus_voltage = 25; Imat = 80 the array matrix will be like this
    Array_1: 4,3
    Array_2: 25
    Array_3: 80.
    I was able to sort out all the channels listed in the *.dbc file in to single array but have no clue how to do the rest of work. Can you please help me in achieving the expected result. Iam attaching the vi and picture which describes where channel information and channel values are passed to the program.
    Thank you,
    - Raghu
    Attachments:
    Output.vi ‏27 KB
    TX_GUI.PNG ‏77 KB

  • How to sort a set of integers

    I have an int array containing a set of integers, and an empty ArrayList.
    I want to find the biggest integer and add it into the ArrayList, and then find the second biggest one and add it into the ArrayList as well, and the 3rd biggest one, as so on.
    How to achieve that? Could anyone write a sample code for me? Thanks in advance!

    Do you really need to follow those steps? Or do you just want to end up with a sorted ArrayList?
    If the latter, you can either sort the array with Arrays.sort and then use Arrays.asList to get a List out of it, or you can use Arrays.asList first, and then call Collections.sort on the resulting list.

Maybe you are looking for

  • Where is the "show pop-up" menu in iTunes 12?

    Instructions on "Import items from other libraries using home sharing" are clear enough, and also appear to be wrong. There is no "show pop-up menu" option in V 12. This makes it impossible to add music or videos from another library.

  • Process description : Invoice Reduction

    Hi I hope someone can explain the process Invoice Reduction. I have made a PO for 10 pc of 100 EUR each - total 1000 EUR. I make a GR for the PO. Then I register an Invoice (MIRO) for 1100 EUR from the vendor and park it because this is wrong. I chan

  • From win to mac osx

    Hi, I am owner a box version of Photoshop CS3 and update CS5 for windows and I now I bought a Macbook pro. I would like to change a licence for Mac OSX, could you help me?

  • From Creame Tinge to Blue Tinge

    I recently removed the creamy yellow tinge to my canvases, but I now seem to have a light blue tinge to it. This occurs in both the 8 bit and 16 bit, but not 32... Any ideas?

  • Having trouble launching after free trial download

    I already downloaded and installed the free trial, but Adobe extension manager is the only thing that is launching.  How can I get into PS. Thanks, Liz