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

Similar Messages

  • 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

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

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

  • Sort Second Element in Array of Strict Type Def Clusters

    I need to sort the an array of strict type def clusters by the second or third element in the cluster.  In the past I have used 1-D array sort and sorted by the first element of the cluster.  When I need to sort by the second, third, or fourth element of the cluster I just break down the cluster and rebuild it placing the desired sort element in the first position of the new cluster.  This works for simple tasks and clusters, but as the cluster gets more complicated this becomes a pain to do this.  There must be a cleaner way to sort by other elements within the original array of strict type def clusters.  Has anyone succeeded in doing this a different way?

    Hello,
    Here's the way I would do it...just create a new cluster array, where each cluster contains two elements...the unbundled item you want to sort by, and the cluster itself.  Then sort the new cluster array, then unbundle the sorted cluster array to get the original clusters (now sorted).  Here is a screenshot:
    There may be a better way, but this is the first thing I thought of.
    -D
    Message Edited by Darren on 03-16-200610:00 AM
    Darren Nattinger, CLA
    LabVIEW Artisan and Nugget Penman
    Attachments:
    Sorted_cluster.jpg ‏30 KB

  • 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

  • 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

  • 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.

  • Sort two one dimensional arrays

    I am having trouble sorting two one dimensional arrays. The first array is int type with ID numbers. I use a bubble sort to sort those. The other array is a string array of video titles. When the first int type array of ID numbers sort, I want the second string type array to follow it. I have tried many things and I can not get it to work properly. Here is what I have for now without the string sort. Can someone help me?
    public class Video
         public static void main(String[] args)
         int[] numID = {168, 397, 102, 39, 239};
         String[] videoTitle = {"Godzilla", "Superman", "Hannibal", "Star Wars", "Men In Black"};
         System.out.println("Here are your selections:");
         System.out.println();
    System.out.print(numID[0]);
         System.out.println("\t" +videoTitle[0]);
         System.out.print(numID[1]);
         System.out.println("\t" +videoTitle[1]);
         System.out.print(numID[2]);
         System.out.println("\t" +videoTitle[2]);
         System.out.print(numID[3]);
         System.out.println("\t" +videoTitle[3]);
         System.out.print(numID[4]);
         System.out.println("\t" +videoTitle[4]);
         System.out.println();
    System.out.println();
    //Sorting ID numbers in ascending order
         int a;
         int b;
         int temp;
    for (a = 0; a < (numID.length - 1); ++a)
         for(b = 0; b < (numID.length - 1); ++b)
              if(numID[b] > numID[b + 1])
                             temp = numID;
                             numID[b] = numID[b + 1];
                             numID[b + 1] = temp;
              System.out.println("Here are your selections in ascending order:");
              System.out.println();
         System.out.print(numID[0]);
              System.out.println("\t" +videoTitle[0]);
              System.out.print(numID[1]);
              System.out.println("\t" +videoTitle[1]);
              System.out.print(numID[2]);
              System.out.println("\t" +videoTitle[2]);
              System.out.print(numID[3]);
              System.out.println("\t" +videoTitle[3]);
              System.out.print(numID[4]);
              System.out.println("\t" +videoTitle[4]);
              System.out.println();
         System.out.println();

    There are ways to do that, of which the simplest would be to switch entries in both arrays at the same time. But since Java is an object-oriented language, the better way to do it would be to make a Video object containing a number and a title, put those objects in an array, and sort the objects.

  • 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 .

  • 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

  • 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

  • Build a 2-dim array

    Hello!
    Now we have this problem: We start with a for-loop that runs as many times as there are numbers of signals. Then we want to create a 2-dim array. We know the numbers of columns but not number of rows... so the numbers of coumns can not be created dynamically like the number of rows. We thought of somethning with the "initialize array" but then one need to know both the numbers of rows and columns... any idea? Thank you and best regards.

    Typically it ie easiest to use a shift register and build the array by adding new rows. (see attached, LV 7.0).
    If you had something different in mind, please explain.
    (If you expect the arrays to become very large, building arrays this way may cause slowdowns due to memory allocations.)
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    BuildArray.vi ‏33 KB

  • Shuffling 2-dim array

    Hello,
    i'm working on a game-project for school, now i need a shuffle of an 2-dim array where i've bound imageIcons to.
    public setRandom () {
    randomArray  = new int[numberRows][numberCollumns]; 
    for (int i=0; i<(numberRows-1); i++)
           for (int j=0; j<(numberCollumns-1); j++)
                  randomArray[i][j] = i;
    }So in the setRandom method i need a shuffle of the randomArray.
    Any ideas ?
    tnx

    i know, i've allready used it, but then i have multiple items and that's not good ...
    import java.util.*;
    public class Shuffle
         public static void main (String[]args)
              int numberRows = 3;
              int numberCollumns = 3;
              Random gen = new Random();  // Random number generator
              int [][] randomArray = new int [numberRows][numberCollumns]; 
              //--- Initialize the array to the ints 0-51
              for (int i=0; i<(numberRows); i++)
                   for (int j=0; j<(numberCollumns); j++)
                       randomArray[i][j] = i*numberCollumns+j;
                       System.out.print(randomArray[i][j]+"   ");
                   System.out.print("\n");
              for (int i=0; i<(numberRows); i++)
                   for (int j=0; j<(numberCollumns); j++)
                           int randomPositionR = gen.nextInt(numberRows);
                           int randomPositionC = gen.nextInt(numberCollumns);
                            int temp = randomArray[i][j];
                           randomArray[i][j] = randomArray[randomPositionR][randomPositionC];
                          randomArray[randomPositionR][randomPositionC] = temp;
                          System.out.print(randomArray[i][j]+"   ");
                   System.out.print("\n");
    }

  • 2 dim array of textField

    Hi
    i have a 2 dim array of textField and i want to fill it with some data
    for example:(this is a part of my applet)
    public void inti()
                Panel table_panel;
                TextField[] [] table1 = new TextField[5][3];
                table_panel = new Panel();
                table_panel.setLayout(new GridLayout(5,3));
                for(int i = 0; i <5; i++)               // for each row
                     for(int j = 0; j < 3 ; j++)       // for each coloum
                     table1[i] [j]= new TextField(); 
                             table_panel.add(table1[i][j]);
                     }// end for
                ClassType obj  ;
                ClassType obj  = new ClassType(x,y);
                table1= obj.fillData();       
    class ClassType{
                           //constructor...........
             public TextField[][] fillData()
              TextField[][] table= new TextField[5][3];
              String s = new String("A");
              for(int i = 0 ; i < 5 ; ++i)
                  for(int j = 0; j<3 ; ++j)
                   table[i][j] = new TextField(s);
              return table;
    }The problem here is:
    the applet is not intialized,should i dispaly table1 again after fillData
    Thanks for you help

    Thanks !
    This is my applet again:
    public void inti()
                Panel table_panel;
                TextField[] [] table1 = new TextField[5][3];
                table_panel = new Panel();
                table_panel.setLayout(new GridLayout(5,3));
                for(int i = 0; i <5; i++)               // for each row
                     for(int j = 0; j < 3 ; j++)       // for each coloum
                     table1[i] [j]= new TextField(); 
                             table_panel.add(table1[i][j]);
                     }// end for
                ClassType obj  ;
                ClassType obj  = new ClassType(x,y);
                table1= obj.fillData();       
    class ClassType{
                           //constructor...........
             public TextField[][] fillData()
              TextField[][] table= new TextField[5][3];
              String s = new String("A");
              for(int i = 0 ; i < 5 ; ++i)
                  for(int j = 0; j<3 ; ++j)
                   table[i][j] = new TextField(s);
              return table;
    }

Maybe you are looking for

  • PO_Creation_turned to be production Issue

    Hi Experts , I have a issue in PO creation  from SOAP to RFC .(me23n SAP) Since the the time we moved the solution to Production , there are other PO (which is alreay been created IN SAP)  , these xml are flowing back forth to XI through the Producti

  • Sending workflow email in HTML format

    Hi Experts, I'd like to know if it is possible to send an HTML email using the workflow email step and HOW. Sample is displaying the simple table in HTML format: <table border="1"> <tr> <th>Header 1</th> <th>Header 2</th> </tr> <tr> <td>row 1, cell 1

  • Color problem printing from iBook G4

    having problems printing photos from an iBook G4 (10.3.9). The colors come out a bit over-saturated and muddy. The same photos printed from my G5 Quad (10.4.6) come out looking fine. I have used the iBook with a Canon ip6600 and ip6000 pixma photo pr

  • Not able to run .msi file on windows XP Version 2002 (SP3)

    Hi I am not able to run .msi file in Windows XP Version 2002(SP3)..I am not able to find the log or the Error.Kindly help

  • Installed AcrobatX Pro, but it crashes right after opening a document

    I just installed the trial version (I think) of Acrobat X Pro.  I want to try out the editing features of the Pro version before installing. I am not able to install Acrobat Pro DC because I am on an older mac operating on 10.7.5. So I was successful