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.

Similar Messages

  • Urgent array sorting question

    I've sorted an array with "Collections.sort(myArrayList)" ..that's ok..but
    in my JList words appare sorted first the uppercase after lowercase
    (i.e. A,CCC,DDDDD,aa,bbb,cc,d)......I want it sort together..
    A lot of thanks for all answer!!

    Use Collections.sort(List list, Comparator c) api.
    Look into java.util.Comparator to create your own custom comparator, for ex.
    public class StringIgnoreCaseComparator implements Comparator {
      public int compare(Object o1, Object o2) {
        String s1 = (String)o1.toLowerCase();
        String s2 = (String)o2.toLowerCase();
        return s1.compareTo(s2);
      public boolean equals(Object obj) {
    }--lichu                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

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

  • String Array Sorting

    Question 1. Anybody know how to easily sort a string array?
    Question 2. Is there any good data base management VI's out there anywhere?
    Thank you

    > Question 1. Anybody know how to easily sort a string array?
    >
    There is this icon in the Array palette called Sort 1D Array. You might want
    to give it a try.
    > Question 2. Is there any good data base management VI's out there anywhere?
    >
    There may be some freebie stuff floating around, but I know that NI has
    an SQL add-on for communicating with most standard databases. As mentioned
    in a previous posting this morning, you can also use ActiveX if that is
    more convenient/easier for you. From my experience, most people find the
    SQL approach easier once they get past the three letter acronym.
    Greg McKaskle

  • Sorting question over state...

    Hi there,
    Anyone know where you amend the over state / hover of an option in a sorting question ???
    Been looking in the object style manager but can't find it in there...
    Thanks in advance...

    You are talking about the partially transparent grey bar that appears when hovering over an answer in the Sequence type of questions. There is no style that can be customized AFAIK. It is not even changing with the included themes. Same is valid for the connecting lines in matching questions that are always black, color cannot be changed for them neither. It is a pity, would recommend you enter a feature request to be able to customize the color of both the hover bar and those lines.
    https://www.adobe.com/cfusion/mmform/index.cfm?name=wishform
    Lilybiri

  • 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 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?)

  • Collator sorting question

    Good Day!
    I have a program, witch uses Collator class object to print numbers in order.
    Collator collator = Collator.getInstance(Locale.US);
         Collections.sort(num, collator);
    for ( i = 0; i < num.size(); i++) {
    String num1 = num.get(i);
    System.out.println("num = " + num1);
    As a result I receive
    num = 1
    num = 1
    num = 10
    num = 10
    num = 100
    num = 100
    num = 101
    num = 101
    num = 102
    num = 102
    num = 2
    num = 2
    num = 20
    But it's necessary to make numbering order as 1 1 2 2 3 3 ...
    I wonder if there is any solution to make Collator class object to understand shorter String sentences as bigger than longer ones. (For an example to understand that 2 is bigger than 10, or 3 is bigger than 20...)
    Thank you for your time!
    Have a nice day!

    What you're describing is most commonly known as the natural sort order (it's also called the intuitive or alphanumeric order). [Here's|http://www.codinghorror.com/blog/archives/001018.html] a good blog post about it. There's no class in the standard libraries that does this, nor is there anything in any public library that I know of. You can find some informal Java implementations (among other languages) by following that link, but here's one I wrote. (Note that it's a Comparator, not a Collator; if you really a Collator, I have one of those too, but it's more experimental.) import java.util.Arrays;
    import java.util.Comparator;
    * <p>A comparator that emulates the "intuitive" sorting used by Windows
    * Explorer.  The rules are as follows:</p>
    * <ul><li>Any sequence of one or more digits is treated as an atomic unit, a
    * number.  When these number units are matched up, they're compared according
    * to their respective numeric values.  If they're numerically equal, but one
    * has more leading zeroes than the other, the longer sequence is considered
    * smaller.</li>
    * <li>Numbers always sort before any other kind of character.</li>
    * <li>Spaces and all punctuation characters always sort before letters.</li>
    * <li>Letters are sorted case-insensitively.</li></ul>
    * <p>Explorer's sort order for punctuation characters is not quite the same
    * as their ASCII order.  Also, some characters aren't allowed in file names,
    * so I don't know how they would be sorted.  This class just sorts them all
    * according to their ASCII values.</p>
    * <p>This comparator is only guaranteed to work with 7-bit ASCII strings.</p>
    * @author Alan Moore
    public class IntuitiveStringComparator<T extends CharSequence>
        implements Comparator<T>
      private T str1, str2;
      private int pos1, pos2, len1, len2;
      public int compare(T s1, T s2)
        str1 = s1;
        str2 = s2;
        len1 = str1.length();
        len2 = str2.length();
        pos1 = pos2 = 0;
        if (len1 == 0)
          return len2 == 0 ? 0 : -1;
        else if (len2 == 0)
          return 1;
        while (pos1 < len1 && pos2 < len2)
          char ch1 = str1.charAt(pos1);
          char ch2 = str2.charAt(pos2);
          int result = 0;
          if (Character.isDigit(ch1))
            result = Character.isDigit(ch2) ? compareNumbers() : -1;
          else if (Character.isLetter(ch1))
            result = Character.isLetter(ch2) ? compareOther(true) : 1;
          else
            result = Character.isDigit(ch2) ? 1
                   : Character.isLetter(ch2) ? -1
                   : compareOther(false);
          if (result != 0)
            return result;
        return len1 - len2;
      private int compareNumbers()
        int delta = 0;
        int zeroes1 = 0, zeroes2 = 0;
        char ch1 = (char)0, ch2 = (char)0;
        // Skip leading zeroes, but keep a count of them.
        while (pos1 < len1 && (ch1 = str1.charAt(pos1++)) == '0')
          zeroes1++;
        while (pos2 < len2 && (ch2 = str2.charAt(pos2++)) == '0')
          zeroes2++;
        // If one sequence contains more significant digits than the
        // other, it's a larger number.  In case they turn out to have
        // equal lengths, we compare digits at each position; the first
        // unequal pair determines which is the bigger number.
        while (true)
          boolean noMoreDigits1 = (ch1 == 0) || !Character.isDigit(ch1);
          boolean noMoreDigits2 = (ch2 == 0) || !Character.isDigit(ch2);
          if (noMoreDigits1 && noMoreDigits2)
            return delta != 0 ? delta : zeroes2 - zeroes1;
          else if (noMoreDigits1)
            return -1;
          else if (noMoreDigits2)
            return 1;
          else if (delta == 0 && ch1 != ch2)
            delta = ch1 - ch2;
          ch1 = pos1 < len1 ? str1.charAt(pos1++) : (char)0;
          ch2 = pos2 < len2 ? str2.charAt(pos2++) : (char)0;
      private int compareOther(boolean isLetters)
        char ch1 = str1.charAt(pos1++);
        char ch2 = str2.charAt(pos2++);
        if (ch1 == ch2)
          return 0;
        if (isLetters)
          ch1 = Character.toUpperCase(ch1);
          ch2 = Character.toUpperCase(ch2);
          if (ch1 != ch2)
            ch1 = Character.toLowerCase(ch1);
            ch2 = Character.toLowerCase(ch2);
        return ch1 - ch2;
      public static void main(String[] args)
        String[] list =
          "foo 03",
          "foo 00003",
          "foo 5",
          "foo 003",
          "foo~03",
          "foo 10far",
          "foo 10boo",
          "foo 10",
          "foo!03"
        Arrays.sort(list, new IntuitiveStringComparator<String>());
        for (String s : list)
          System.out.println(s);
    }

  • 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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Maybe you are looking for

  • My safari keeps crashing and my youtube keeps getting playback errors. Help!

    I am currently usin an iPod 4th generation with IOS 6.1.5. Whenever I open up the safari app, it will stay blank and crash after about a minute or so. Following, I cannot watch videos on my YouTube app beecause it keeps receiving a playback error. I

  • RFC connection from SAP Data services to SAP ECC

    We have data services set up in linux machine. I am trying to set up RFC connection between data services and SAP ECC. From data management console after creating RFC connection i am getting "RFC_bad_connection" error message. Username , password, sy

  • Application not appearing

    Hi Experts, I having created a custom wedbynpro application using FPM, but when I created the Application of the webdynpro component the applciation is not seen. However, when I go to the Package and under the hierarchy 'Webdynpro applications'  I am

  • HT4972 How do I upgrade my iPOD Touch from iOS 4.2.1 to 5?

    How do I upgrade my iPOD Touch from iOS 4.2.1 to 5?  I've reset it, erased it, but still won't install iOS5.

  • Installation OEL 5.4

    hi how to install OEL 5.4 from kernel source code? i am using OEL 5.2,now i want build the OEL 5.4 and nstall it from the source code.how to do that? regards