Array Sort

Dear Friends;
I am stuck with the following problem.
I have an array as follows:
Array: {(1st row is Index, i.e. 1-6 or A-F); 2nd row is the corrospending value}
1      2    4      3    1    6    2    6
26    6    46    6    6    9    6    9
I want to sort the avobe array as follows:
Desired Table: [6x7], {(1st col is Index, i.e. 1-6 or A-F); 2nd to 8th col are the corrospending value, missing one filled by 0}
1    6    26    0    0    0    0    0
2    6    6     0    0    0    0    0
3    6    0     0    0    0    0    0
4    46   0    0    0    0    0    0
5    0    0    0    0    0    0    0
6    9    9    0    0    0    0    0
Any help would be appreciable.
Regards-K

Hi mamunk2,
Do you have a vi related to this problem which you have worked on?
There is an example of the 2D sorter:
https://decibel.ni.com/content/docs/DOC-12264
https://decibel.ni.com/content/docs/DOC-17440
https://decibel.ni.com/content/docs/DOC-13719
http://www.ni.com/example/27502/en/
As for the missing one, you can create the 8x8 array using "Initialize Array" with the size value = 8 and the initial value = 0 which you fix. The final result of sorted array will replace the 8x8 array which you created using "Replace Array Subset".
Hope that helps,
Warmest regards,
Lennard.C 
Learning new things everyday...

Similar Messages

  • Doubt in working of Arrays.sort method. help needed !!!!

    Hello Friends,
    I am not able to understand output of Arrays.sort method. Here is the detail of problem
    I wrote one program :
    public static void main(String[] args) throws ClassNotFoundException
         Object[] a = new Object[10];
         a[0] = new String("1");
         a[1] = new String("2");
         a[2] = new String("4");
         a[3] = new String("3");
         a[4] = new String("5");
         a[5] = new String("20");
         a[6] = new String("6");
         a[7] = new String("9");
         a[8] = new String("7");
         a[9] = new String("8");
    /* Sort entire array.*/
         Arrays.sort(a);
         for (int i = 0; i < a.length; i++)
         System.out.println(a);
    and output is :
    1
    2
    20
    3
    4
    5
    6
    7
    8
    9
    Question : Does this output is correct? If yes then on which basis api sort an array? I assume output should be 1 2 3 4 5 6 7 8 9 20.
    Can here any one please explain this?
    Thanks in advance.
    Regards,
    Rajesh Rathod

    jverd wrote:
    "20" and "3" are not numbers. They are strings, and "20" < "3" is exactly the same as "BA" < "C"The above is
    ... quote 20 quote less than quote 3 quote...
    but shows up as
    ... quote 20 quote less than quote...
    Weird.

  • Structure of arrays sort

    Hi, I have a structure of arrays as follows.
    The Structure is session.cart
    my arrays are session.cart.foodname[ ]
    session.cart.comments[ ]
    session.cart.name[ ]
    session.cart.price[ ]
    All of these arrays correspond to each other, so
    session.cart.name[1] may be John, who ordered a cheeseburger
    (session.cart.foodname[1]). So i need to sort these by the persons
    name and have the other 3 arrays sort with them, so they still
    correspond to each other. Can anyone help me with this? Ive looked
    over the structsort function but cant figure out how to apply it to
    a structure of arrays. Thanks for the help.

    I would avoid using multiple arrays, which have to refer to
    each other - without really having a proper way to execute the
    plan. Structures are better for this. I created an example, which
    you might try out, and see if it fits your needs:
    <cfscript>
    session.cart.item = structnew();
    // use the name also as a key
    session.cart.item["john"]=structnew();
    session.cart.item["john"]["name"] = "john";
    session.cart.item["john"]["foodname"] = "Ribs";
    session.cart.item["john"]["price"] = "13.99";
    session.cart.item["john"]["comments"]="Johncomment";
    session.cart.item["mary"]=structnew();
    session.cart.item["mary"]["name"] = "mary";
    session.cart.item["mary"]["foodname"] = "Apple";
    session.cart.item["mary"]["price"] = "0.49";
    session.cart.item["mary"]["comments"]="Marycomment";
    session.cart.item["adam"]=structnew();
    session.cart.item["adam"]["name"] = "adam";
    session.cart.item["adam"]["foodname"] = "Cake";
    session.cart.item["adam"]["price"] = "4.99";
    session.cart.item["adam"]["comments"]="Adamcomment";
    // the following line actually does all you ever wanted.
    arrayToList() is just a bonus
    // for easy-to-understand-output in the end. More elegant
    solutions may exist. :-)
    nameList =
    arrayToList(structSort(session.cart.item,"textnocase","asc","name"));
    </cfscript>
    <cfoutput>
    <cfloop list="#nameList#" index="currentName">
    #session.cart.item[currentName].name#<BR>
    #session.cart.item[currentName].foodname#<BR>
    #session.cart.item[currentName].price#<BR>
    #session.cart.item[currentName].comments#<BR>
    <HR>
    </cfloop>
    </cfoutput>

  • Arrays.sort() issue when Numbers are a string!

    Hey guys -- here is my problem.
    I am working on a TOP TEN SCORES mechanism for a trivia game. I have read in the score and the players name from a file. SO I have 2 different arrays topScores[] and topNames[] ---
    Now if someone plays the game and has a higher score than the lowest score, they get to put their score and name in the file and replace the low score.
    HOWEVER -- I do not know how to sort topSCORES[] and then make whatever sorted changes apply also to the topNAMES[] array.
    SO I thought - HEY I will concatenate the topScores and topNames into a single String array. And then SORT! This sounded like a great idea until I realized that the following will happen:
    100 tvance (first one)
    1000 dvance (second score)
    250 danderson (third score) !!!
    See my problem? When I sort this way - it is sorting alphabetically so it will put a 1000 score before a 200-900 score! ---
    **I hope I explained this adequately -- can someone help? Is there a way to sort the topScores array and have it also change the order of the topNames array as well?

    Create a new class - HighScore, which has a highScore and a name?Yup. This technique even has a name: object-oriented programming!
    Demo:
    import java.util.*;
    public final class HighScore implements Comparable<HighScore> {
        private final int score;
        private final String name;
        public HighScore(int score, String name) {
            if (name == null)
                throw new NullPointerException();
            this.score = score;
            this.name = name;
        public int getScore() {
            return score;
        public String getName() {
            return name;
        public int compareTo(HighScore that) {
            if (this.score < that.score)
                return -1;
            else if (this.score > that.score)
                return +1;
            else
                return this.name.compareTo(that.name);
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            else if (obj instanceof HighScore) {
                HighScore that = (HighScore) obj;
                return this.score == that.score && this.name == that.name;
            } else
                return false;
        public int hashCode() {
            return score ^ name.hashCode();
        public String toString() {
            return score + " " + name;
        //demo
        public static void main(String[] args) {
            HighScore[] top = {
                new HighScore(250, "danderson"),
                new HighScore(1000, "dvance"),
                new HighScore(100, "dvance")
            Arrays.sort(top);
            for(int i=0; i<top.length; ++i) {
                System.out.println(top);
    If you are using an older version of Java (1.4 or earlier), the generics won't be
    recognized. In that case the class definition would begin:
    public final class HighScore implements Comparable {And the compareTo method would begin:
    public int compareTo(Object obj) {
        HighScore that = (HighScore) obj;Good luck!

  • Java.util.Arrays.sort for Vector

    I used the java.util.Arrays.sort to sort an array based on the method below.
                  java.util.Arrays.sort(array, 0, total, new ComparatorX());
               repaint();
                class ComparatorX implements java.util.Comparator
              public int compare( Object p1, Object p2){
                   int x1=((Point)p1).x;
                   int x2=((Point)p2).x;
                   if(x1>x2)
                                return 1;
                   if(x1>x2)
                                return -1;
                   return 0;
         }I've since changed the array to a vector. Is there anyway I can keep the comparator. Or how can I sort the vector based on the above method.

    BTW: Don't know if it's just a typing mistake, but your code contains an error:
    class ComparatorX implements java.util.Comparator     {
       public int compare( Object p1, Object p2) {
          int x1=((Point)p1).x;
          int x2=((Point)p2).x;
          if (x1>x2) {
             return 1;
          if (x1>x2) {  // Should be: if (x2 > x1) ...
             return -1;
          return 0;

  • TreeSet vs Collection.Sort / Array.sort for Strings

    Gurus
    I am pondering weather to use TreeSet vs the Collections.sort / Array.sort for sorting Strings.
    Basically I have a list of Strings, i need to perform the following operations on these Strings
    1) Able to list Strings starting with a Prefix
    2) Able to list Strings Lexically greater than a String
    Any help would be greatly appreciated!
    Thanks a bunch

    SpaceShuttle wrote:
    Gurus
    I am pondering weather to use TreeSet vs the Collections.sort / Array.sort for sorting Strings.
    Basically I have a list of Strings, i need to perform the following operations on these Strings
    1) Able to list Strings starting with a Prefix
    2) Able to list Strings Lexically greater than a String
    Any help would be greatly appreciated!
    Thanks a bunchBig-O wise, there's no difference between sorting a list of N elements or inserting them one by one in a tree-set. Both take O(n*log(n)). But both collections are not well suited for looking up string that start with a certain substring. In that case you had better use a Patricia tree (or Radix tree).
    Good luck.

  • Relate to Array.sort(), urgent help~~

    I am using a class for store the data
    then I need to sort them
    is it the vector which want to sort is needed in same class???
    because I use other file to access them~~
    The following code:
    public Test()
    Person person;
    Vector v = new Vector();
    v.add(new Person("Johnson","Fox");
    v.add(new Person("Johnson","David");
    Object[] a = v.toArray();
    Arrays.sort(a);
    public int compareTo(Object dd,Object ww)
    if (dd instanceof Person && ww instanceof Person)
    Person d = (Person) dd;
    Person w = (Person) ww;
    return w.lname.compareTo(d.lname);
    else
    return 0;
    the code doesn't work btit can compile, can anyone help me to solve it??
    thank you for your time~~

    In Person.java use the following:
    class Person
       public int compareTo(Object cmpPerson)
          if (cmpPerson instanceof Person)
             return this.lname.compareTo( ((Person)cmpPesron).lname );
          else
             return 0;
    }

  • Array.sort() question

    I've been looking at Arrays and the Comparator interface. But I don't understand the sorting results:
    import java.util.*;
    import java.io.*;
    class SearchObjArray {
         public static void main(String[] args) {
              Console con=System.console();
              if (con==null) System.exit(1);
              String[] sa={"one","two","three","four"};
              Arrays.sort(sa);          
              con.format("The sorted string:%n");          
              for(String s: sa)
                   con.format("%s ",s);
              //four,one,three,two
              con.format("%nA binary search for \"one\": one=%s%n",Arrays.binarySearch(sa,"one"));
              //one=1, as expected. The binarySearch found "one" in position 1 of the sorted array.
              ReSortComparator rs=new ReSortComparator();     
              con.format("A binary search for \"one\" using the resort comparator on the string array: one=%s%n",Arrays.binarySearch(sa,"one",rs));
              //one=-1<====WHY -1? Why is the insertion point 0?
         static class ReSortComparator implements Comparator<String> {
              public int compare(String a, String b) {
                   return b.compareTo(a);
              

    You have to search using the same ordering rules as how the array is sorted. You sorted with one set of rules (String's natural ordering) and searched with a different set of rules (the opposite ordering, as determined by your comparator). That's the same as trying to do a binary search on an unsorted array. Since one of the preconditions of binary search is that the array be sorted, it shouldn't be surprising that you get odd results.

  • Array sort with objects?

    hits = searcher.search(query);
    //java.util.Vector sortHits = new java.util.Vector ();
    int[][] sortHits = new int[hits.length()][1];
    // assign values to array
    int teller = 0;
    for (int i = 0; i < hits.length(); i++)
         Document doc = hits.doc(i);
         String absnumtxt = doc.get("absnumtxt");
         if(sAllCookies.indexOf(absnumtxt) >= 0){
              sortHits[0] = Integer.parseInt(absnumtxt);
              teller++;
              continue;
    But the method Arrays.sort(sortHits); causes a ClassCastException error. Somebody an idea to solve this?
    The structure is:
    sortHits[0][0] = 2
    sortHits[1][0] = 0
    sortHits[2][0] = 0
    sortHits[3][0] = 0
    sortHits[4][0] = 0
    sortHits[5][0] = 0

    A two-dimentional array is an array of array of something.
    Sorting a two-dimentional array requires a Comparator, because you compare uni-dimentional arrays, and arrays are not naturally comparable.
    (BTW, why declaring a two-dimentional array here? you set the second dimention length to 1... a simple array would make it, no?)

  • Arrays.sort

    Why is the Arrays.sort method defined as
    public static void sort(Object[] a)
    instead of
    public static void sort(Comparable[] a) ?

    jverd wrote:
    This way we can sort an array whose elements are all mutually comparable, even if the array itself is not declared to be of a Comparable type. I can't think of a specific use case where that would be useful, but it's the only reason I can think of for deliberately making that decision.Dear jverd, I am not sure I understand the possible case you are referring to. I tried the following code and it gives a runtime Exception.
      public class ArraysTest {
        public static void main(String argsp[]){
            Data [] dr = new Data[4];
            dr[0] = new Data(4);        dr[1] = new Data(0);
            dr[2] = new Data(8);        dr[3] = new Data(3);
            Arrays.sort(dr);
            System.out.println(dr);
    class Data{
        Integer i;
        public Data(int j){
            i = j;
        public int compareTo(Data d){
            if(i<d.i)
                return -1;
            if(i==d.i)
                return 0;
            return 1;
        @Override
        public String toString(){
            return i.toString();
    }<font color="red">
    Exception in thread "main" java.lang.ClassCastException: temp.Data cannot be cast to java.lang.Comparable
    [Ltemp.Data;@b37c60d
    at java.util.Arrays.mergeSort(Arrays.java:1144)
    at java.util.Arrays.sort(Arrays.java:1079)
    </font>

  • Multidimensional Array Sort

    Please help. I am very new to java and trying to build a multidimensional array. I have two variables 1)item_name and 2)item_value. These are values that I obtain by looping through a database result set. I need to build and array that can hold these variables. Once the multidimensional array is built I need to be able to sort it by item value.
    For example I would like to do something like this:
    while (rs.next)
    array.name = item_name
    array.value = item_value
    end
    array.sort(value)
    Thanks for any help!

    Don't use a multidimensional array. Use an array of objects, where the objects are of a class that you define. It might be something as simple as class Item that just has two fields--name and value--and their getters and setters. Or maybe just getters if you want the class to be immutable.
    Have the class implement Comparable and sort on value.
    If you sometimes want to sort on value and sometimes on name, then you'll need to either define two Comparators (one for name, one for value) or make the class Comparable on whichever is the more "natural" ordering and define a Comparator for the other one.
    Either put them in an array and use one of the java.util.Arrays.sort methods to sort them, or put them in a List (java.util.LinkedList or java.util.ArrayList) and use Collections.sort to sort them.

  • Array.sort(Object[], comparator) problems

    I have been trying for days to figure out how to sort my array of geneInfo ono the field score1.
    when i try to use Arrays.sort(gInfo, new score1Comp()) it turns all of the array null.
    class score1Comp implements Comparator
    public int compare(Object o1, Object o2)
    geneInfo g1 = (geneInfo)o1;
    geneInfo g2 = (geneInfo)o2;
    // added these checkers to get rid of nullPointerException, but checked to see that most are non null
    if(g1==null&&g2==null)
    return 0;
    if(g1==null)
    return -1;
    if(g2==null)
    return 1;
    if(g1.getScore1() == g2.getScore1())
    return 0;
    else
    double temp = g1.getScore1() - g2.getScore1();
    System.out.println("score g1 - score g2: " + temp);
    System.out.println("rounded: " + (int)Math.round(temp));
    return (int)Math.round(temp);
    public boolean equals(Object obj)
    return obj.equals (this);
    }

    You have sorting your array with null to be the least on value object. For example here:
    MyObject[] objs = new MyObject[1000];
    objs[0] = new MyObject(3);
    objs[1] = new MyObject(2);
    objs[2] = new MyObject(1);
    Arrays.sort(objs, new score1Comp());Guess what the result would be? Your array would have the first 997 elements become null and the last 3 would be sorted to (1), (2), (3).
    So the cause is how your Comparator treats the null value. The solution could be to make sure your sorting array is filled correctly, or reverse the return 1/-1 for the null treatment.
    --lichu                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Java Array Sorting

    I am having problems sorting this array in ascending and descending order. I also need to intitialize a reset button.
    Thanks! :>)
    import java.util.*;
    import java.io.*;
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Combine3 extends Applet implements ItemListener
    Label lblTitle = new Label("Sorting");
    Label lblTitle2 = new Label("Please select Sort option");
    CheckboxGroup chkItems = new CheckboxGroup();
    Checkbox chkAscending = new Checkbox("Ascending)", true, chkItems);
    Checkbox chkDescending = new Checkbox("Descending)", false, chkItems);
    Checkbox chkHidden = new Checkbox("",true,chkItems);
    Button btnSort = new Button("SORT");
         TextField txtOne = new TextField("-3");
         TextField txtTwo = new TextField("0");
         TextField txtThree = new TextField("5");
         //Textfield txtFour = new Textfield("33");
         //Textfield txtFive = new Textfield("23");
         //Textfield txtSix = new Textfield("1");
         //Textfield txtSeven = new Textfield("");
         //Textfield txtEight = new Textfield("-3");
         //Textfield txtNine = new Textfield("-3");
         //Textfield txtTen = new Textfield("-3");
    public void init()
         add(lblTitle);
         add(lblTitle2);
         add (txtOne);
         add (txtTwo);
         add (txtThree);
         add(chkAscending);
         add(chkDescending);
         add(btnSort);
         setBackground(Color.cyan);
         //     add(lblDisplay);
         chkAscending.addItemListener(this);
         chkDescending.addItemListener(this);
         //btnSort.addActionListener(this);
    /* public void actionPerformed(ActionEvent e) {
         chkHidden.setState(true);
    //Executed when checkbox is selected or unselected
    public void itemStateChanged(ItemEvent e) {
         //sort in ascending order
         String strInput;
         int intArray[] = new int[3];
         //for (int x=0; x<intArray.length; x++)
              strInput = txtOne.getText();
              intArray[0] = Integer.parseInt(strInput);
              strInput = txtTwo.getText();
              intArray[1] = Integer.parseInt(strInput);
              strInput = txtThree.getText();
              intArray[2] = Integer.parseInt(strInput);
         if (chkAscending.getState() == true)
         Arrays.sort(intArray);
         // display ascending order
         //for(int i=0; i<intArray.length; i++)
              txtOne.setText(" " + intArray[0]);
              txtTwo.setText(" " + intArray[1]);
              txtThree.setText(" " + intArray[2]);
         //lblTitle2.setText("Ascending: " + i + "Value: " + intArray);
         // sort in descending order
         else if (chkDescending.getState() == true)
    for (int i=intArray.length-1; i >= 0; i--)
              for(int j=1; j <= i; j++)
                   if (intArray[j-1] < intArray[j])
              int temp = intArray[j-1];
                   intArray[j-1] = intArray[j];
                   intArray[j] = temp;
                   } // end if
    } // end for
         } // end for
         // display descending order
         for(int i=0; i<intArray.length; i++)
         lblTitle2.setText("Descending: " + i + " Value: " + intArray[i]);
    } // end else if
    } //End itemStateChanged
    } //End Class

    You might take a quick look at the following link regarding sorting arrays. The "Arrays.sort(xxx)" mechanism works well.
    http://developer.java.sun.com/developer/TechTips/1999/tt0923.html

  • Sort 2 arrays - Arrays.sort()

    I sorted Arrays.sort(arr1);
    I also sorted my second array using same method Arrays.sort(arr2);
    Now I want to sort both my arrays in to one.. How do I do this?

    public class CopyArray
      public static void main(String args[])
        int[] x = {4,2,5,1};
        int[] y = {0,-1,3,6};
        int[] combined = new int[x.length + y.length];
        System.arraycopy(x,0,combined,0,x.length);
        System.arraycopy(y,0,combined,x.length,y.length);
        java.util.Arrays.sort(combined);
        for (int i = 0; i < combined.length; i++)
          System.out.print(" " + combined);
    System.out.println();

  • Sort seq diff between rowsorter and Arrays.sort

    I am building a JTable using cols String[] array and Object[][] array.
    When I initially build the Object[][] array I sort a temp String array using Array.sort (Arrays.sort(tempstring,String.CASE_INSENSITIVE_ORDER);)then I load the Object[][] array in the resulting sequence.
    After building the table I use setAutoCreateRowSorter(true) to allow sorting on any column.
    The problem is that the two methods of sorting appear to handle special characters differently.
    Example:
    Initial sequence of array after sorting:
    co
    Compnay Info
    cust-ord
    Customer Info
    Order Header Info
    I now load the table and it appears in the same sequence
    Once I click on the table header the seq changes to:
    co
    Compnay Info
    Customer Info
    cust-ord
    Order Header Info
    I have no preference on either sequence, I would just like the results the same on both the initial load and subsequent user requested sorts.
    Thx in advance,
    BAJH

    If I do not use String.CASE_INSENSITIVE_ORDER on the Array.sort the initial sequence is:
    Compnay Info
    Customer Info
    Order Header Info
    co
    cust-ord
    Then when I click on the table header it changes to:
    co
    Compnay Info
    Customer Info
    cust-ord
    Order Header Info
    So String.CASE_INSENSITIVE_ORDER is more alike in the results.
    The only difference appears to be the special character. "-"
    So your solution is not accurate, Thx anyway...

  • Need Help with Array.sort and compare

    Hi
    I have a big problem, i try to make a java class, where i can open a file and add new words, and to sort them in a right order
    Ok everthing works fine, but i get a problem with lower and upper cases.
    So i need a comparator, i tried everything but i just dont understand it.
    How do i use this with Array.sort??
    I hope someone can help me

    Okay, you want to ignore case when sorting.
    There are two possibilities: Truly ignore case, so that any of the following are possible, and which one you'll actually get is undefined, and may vary depending on, say, which order the words are entered in the first place:
    English english German german
    english English german German
    English english german German
    english English German german
    The second possibility is that you do consider case, but it's of lower priority--it's only considered if the letters are the same. This allows only the first two orderings above.
    Either way, you need to write a comparator, and call an Arrays.sort method that takes both array and Comparator.
    The first situation is simpler. Just get an all upper or lower case copy of the strings, and then compare thosepublic int compare(Object o1, Object o2) {
        String s1 = ((String)o1).toUpper();
        String s2 = ((String)o1).toUpper();
        return s1.compareTo(s2);
    } You'll need to add your own null check if you need one.
    For the second way, your comparator will need to iterate over each pair of characters. If the characters are equal, ignoring case, then you compare them based on case. You pick whether upper is greater or less than lower.
    Of course, the need to do this assumes that such a method doesn't alrady exist. I don't know of one, but I haven't looked.

Maybe you are looking for

  • Master data load: texts are not loaded

    Hi friends, Trying to load BW Hierarchy(0COSTCENTER) to BPC dimension(P_CC). Loadedd master data & text data using package "Import master data from BI infoobject"(/CPMB/IMPORT_IOBJ_MASTER), but EVdescription (texts) are not uploaded ino BPC dimension

  • Wireless connection for officejet 4500

    I just replaced my router and now I'm having problems reconnecting my officejet 4500.

  • Closing Internal Orders

    When I try to close an IO, I get an error message "(KO 447) There is still a purchase order commitment for ORD 6041700".  The related PO line item is already flagged "Delivery Complete" and "Final Invoice", but still won't close.  The only way I can

  • URL Target - conditions on javascript:confirmDelete()

    Is it possible to change the text of the confirmDelete() dialog that pops up when the user clicks 'Submit' button? Before submitting the form the user will either click BUTTON A and continue completing the fom in one way, OR click BUTTON B and comple

  • Recording with Logic and Mackie Onyx?

    Has anyone an opinion about how well these new Mackie Onyx mixers w/ the Firewire Card perform working with Logic Pro 7? Specifically in terms of tracking 16 live channels simultaneously and getting low latency as well as tracking out thru Logic and