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.

Similar Messages

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

  • Fastest Array sort method =Flashsort?

    i'm using Array.sort(object) method to sort the array but the running time is getting slower and slower as the size and number of arrays increase.
    As far as i know, Java uses quicksort for Array.sort() and the running time is O(nlogn) with n is the size of the array. Even it's one of the fastest algorithm out there, it will take too long to sort a big number of array.
    I heard that flashsort is the fastest algorithm with running time of O(n). This algorithm is by Dr. Karl-Dietrich Neubert's.
    Anyone wrote one class already that i can use like Flashsort.sort(array a) ?

    There are various implementations of this algorithm on
    this page:
    http://www.neubert.net/Flacodes/FLACodes.html
    I haven't studied it but I had the impression that you
    need to assume some things about the input data to get
    O(n) time complexity; this isn't the only O(n) sorting
    algorithm (radix sort is O(n) too).I think you assume nothing about data. In stead, you need more memory (20%) to sort using FlashSort.
    It is kind of memory for speed sorting. Here is the java code by Roseanne Zhang if you are interested:
    * FlashSort.java
    * Dr. Karl-Dietrich Neubert's Flashsort1 Algorithm
    * http://www.neubert.net/Flapaper/9802n.htm
    * Translation of algorithm into Java by Roseanne Zhang 
    * http://www.webappcabaret.com/javachina
    * Timing measurement included
    * Full functional application
    class FlashSort
        static int   n;
        static int   m;
        static int[] a;
        static int[] l;
         * constructor
         * @param size of the array to be sorted
        public static void flashSort(int size)
            n = size;
            generateRandomArray();
            long start = System.currentTimeMillis();
            partialFlashSort();
            long mid = System.currentTimeMillis();
            insertionSort();
            long end = System.currentTimeMillis();
            // print the time result
            System.out.println("Partial flash sort time     : " + (mid - start) );
            System.out.println("Straight insertion sort time: " + (end - mid) );
         * Entry point
        public static void main(String[] args)
            int size = 0;
            if (args.length == 0)
                usage();
                System.exit(1);
            try
                size = Integer.parseInt(args[0]);
            catch (NumberFormatException nfe) {
                usage();
                System.exit(1);
            FlashSort.flashSort(size);
         * Print usage
        private static void usage()
            System.out.println();
            System.out.println("Usage: java FlashSort n ");
            System.out.println("       n is integer which is the size of array to sort");
         * Generate the random array
        private static void generateRandomArray()
            a = new int[n];
            for (int i=0; i < n; i++)
                a[i] = (int)(Math.random() * 5 * n);
            //printArray(a);
            m = n/20;
            if (m < 30) m = 30;
            l = new int[m];  
         * Partial flash sort
        private static void partialFlashSort()
            int i = 0, j = 0, k = 0;
            int anmin = a[0];
            int nmax  = 0;
            for (i=1; i < n; i++)
                if (a[i] < anmin) anmin=a;
    if (a[i] > a[nmax]) nmax=i;
    if (anmin == a[nmax]) return;
    double c1 = ((double)m - 1)/(a[nmax] - anmin);
    for (i=0; i < n; i++)
    k=(int)(c1*(a[i] - anmin));
    l[k]++;
    //printArray(l);
    for (k=1; k < m; k++)
    l[k] += l[k-1];
    int hold = a[nmax];
    a[nmax]=a[0];
    a[0]=hold;
    int nmove = 0;
    int flash;
    j=0;
    k=m-1;
    while (nmove < n-1)
    while (j > (l[k]-1))
    j++;
    k = (int)(c1 * (a[j] - anmin));
    flash = a[j];
    while (!(j == l[k]))
    k = (int) (c1 * (flash - anmin));
    hold = a[l[k]-1];
    a[l[k]-1]=flash;
    flash = hold;
    l[k]--;
    nmove++;
    //printArray(a);
    * Straight insertion sort
    private static void insertionSort()
    int i, j, hold;
    for (i=a.length-3; i>=0; i--)
    if (a[i+1] < a[i])
    hold = a[i];
    j=i;
    while (a[j+1] < hold)
    a[j] = a[j+1];
    j++;
    a[j] = hold;
    //printArray(a);
    * For checking sorting result and the distribution
    private static void printArray(int[] ary)
    for (int i=0; i < ary.length; i++) {
    if ((i+1)%10 ==0)
    System.out.println(ary[i]);
    else
    System.out.print(ary[i] + " ");
    System.out.println();

  • Selection Sort Method help

    The method below will not compile. The error reads" void is an invalid type for the variable selectionSort". What should I do? Also how would I invoke the method?
    public static void selectionSort(double[] score, String[] name)
             for (int i=scores.length-1; i>=1; i--)
               double currentMax=scores[0];
               int currentMaxIndex=0;
               for (int j=1; j<=i; j++)
                 if (currentMax<scores[j])
                   currentMax=scores[j];
                   currentMaxIndex=j;
               if (currentMaxIndex!=i)
                  scores[currentMaxIndex]=scores;
         scores[i]=currentMax;
         String temp=names[currentMaxIndex];
         names[currentMaxIndex]=names[i];
         names[i]=temp;
         }Thanks.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    meepton wrote:
    show me how.Why? you didn't write it, you don't understand it so I don't see any beneficial reason to help you. I suggest reading some tutorials about creating and using methods.
    Mel

  • Object SELFITEM/SENDTASKDESCRIPTION method help needed

    Hi All,
    I am working on Credit Release workflow for SD documents.
    -     I have a mail sending step in workflow definition.
    -     In this step I have created a task which is using SELFITEM object & SENDTASKDESCRIPTION method.
    -     When I logged into the system with default language (EN) I can see all the details in the mail body.
    -     When I logged into the system with some other language (Say JA) I can not see all the information in mail body
    -     Some information like currency of the order value is not shown in mail body when logged in with some other language.
    Can anybody will help me to resolve this issue.
    Thank you all in advance.
    Best Regards,
    Deepa Kulkarni

    Try like below:
    Data:  lv_logon TYPE t002-spras,
              lv_text   TYPE char80.
                 lv_logon = sy-langu
                 if lv_logon EQ 'E'.
                     lv_text = "English text"
                 elsif lv_logon EQ 'J'.
                   lv_text = " Japanese text".
                endif.
    SWC_SET_ELEMENT CONTAINER 'TEXT' lv_text.
    Note...if your content is having multiple lines...then you can go with table parameter instead of variable.

  • Creating a byte Array dynamically.Urgent Help needed.

    Hi there,
    I need to create a byte Array with the values
    derived from the array and then am passing this byte array
    to a method.
    Example :
    public static void main(String[] args) throws IOException {
    char chars[] = {'a','j','a','y'};
    byte[] b = {
    (byte) chars[0],(byte) chars[1],(byte) chars[2],(byte) chars[3],
    //** Send name to a server.
    sendRequest(b);
    This is all right.
    But here I know the size of the character array chars.
    If it had more than 4 characters or less than 4,
    is there a way to create the byte array dynamically based on the values in the character array?
    Please can some one help me with creating a byte array on the fly?
    Has anyone understood my question please?
    A response is much much appreciated.

    The actual problem is this.
    The byte array already has some fixed values to it
    and i need to append the values of the character array
    to this byte array
    ie
    char chars[] = {'a','j','a','y'};
    byte b[] = {
    // Predefined values
    (byte) 0x01, (byte) 0x7E, (byte)0x03
    // I have to add the values from the array here
    (byte) chars[0], (byte) chars[1]....
    How can I add these values.? The size of the character array
    can vary

  • Sorting Issue Help Needed Badly

    *+{color:#000000}*Hello All,*+*
    I am having a small piece of code in my project that retrieves file names from a directory applying filename filter. Well i am happening to get them fine in sorted order. But when i implement that program in other machine it happens that all the file names are in unsorted order. I applied several sorting techniques Collator, SortedSet etc. no luck+</stro
    Any could help me on this. By the way my development machine has JDK 1.6 while implementing system has only JRE1.5 which comes embedded with jBase. Consider i have nothing to do with jBase thats another team's project.{color}+*
    FilenameFilter fileNameFilter = new SEPITFilenameFilter(".JPG");
    String slideURLs[] = slideBase.list(fileNameFilter);
    slideURLs = Storage.sortStringsInAscending(slideURLs);
    public static String[] sortStringsInAscending(String[] array)
    Collator collator = Collator.getInstance();
    CollationKey collationKey[] = new CollationKey[array.length];
    for(int k=0; k<array.length; k++)
    collationKey[k] = collator.getCollationKey(array[k].trim());
    int i=0;
    boolean swapped = true;
    while(swapped)
    swapped = false;
    i++;
    for(int j=0;j<(array.length-i);j++)
    int comparator = collationKey[j].compareTo(collationKey[j+1]);
    if(comparator > 0)
    String tempString = array[j];
    array[j] = array[j+1];
    array[j+1] = tempString;
    swapped = true;
    return array;
    }

    Well, if you simply want to sort the file names themselves, build a List and then call Collections.sort(). String already has a comparator built-in that will sort them ascending for you.
    If you want to customize things, write a Comparator. Then call Collections.sort().
    - Saish

  • Work with images in netBeans Help needed !

    Hai Guys,
    I have problem in inserting image in JFrame(In netBeans). Can any one tell me the way to insert an image to JFrame and save that image in my SQL database?
    Guys this is a very important task to me so please help me !
    Thanks for watching / replying

    If you are using net beans use the image view if it and insert the picture of the customer in to explicitly in to the column you want to put in and check the code generated behind.
    So you come to how to insert the picture in to the pane of the Jframe.
    Inseting the particular image in to database
    do as he said "BLOB" as your datatype and store the image.
    I think in your Jframe you might be taking the input from the user and posting it to show the user what he has entered and then saving it into the database.
    so directly put the input data first in to the required column where you are showing user the data what he entered and then on submit/save button call action performed method to save the data in the database

  • My Newly bought Blackberry Classic left side speaker is not working.... Help needed...!!!!!

    Dear All,
    Please kindly help me on this, I am from Pakistan and I got my Blackberry Classic delieved to me from USA my cousin bought it from online blackberry store and brought it by hand. Just now i have noticed that my blackberry classic left side speaker is not working only ringing sound music sound and loudspeaker sounds are coming from the right side of the speaker.
    Has anyone faced this problem with his new classic and what should i do?
    Please help or guide me
    Solved!
    Go to Solution.

    Knowing this that classic comes up with only one speaker did broke my heart  But to be honest the sound is excellent even at high volume the sound does not distort. its a genuien stereo speaker

  • Menu Button not working at all..Please help needed urgently for deadline.

    I have used all the suggestions I can find in the forum. Nothing is working.
    I am trying to draw button rectangle on a still background for a menu. Draging the pointer doesn't do anything. I have tried to import a tutorial with menu and buttons within it. When loading the project assets the import stops at "Loading menu" and does not proceed.
    I am using suitcase fusion for a font manager.I have reinstalled the DSP a few times without any success.
    I have spent three nights trying to solvge the problem and I am running out of time for the project delivery help is need urgently

    Your key is the "suitcase fusion for a font manager" line.
    There is a bug where you won't be able to create a button if you have a bad font, or a duplicate font, installed.
    First try shutting off all of the fonts you have open with Suitcase, and see if that helps. If so, open one suitcase at a time until you figure out which font is the culprit.
    If shutting off all but the basic System fonts does not help, you might have to reinstall your system, or somehow update your core System fonts. I don't know how to do that, but there was a recent article at http://www.tidbits.com/ that discussed fonts and their maintenance. But ultimately it's a font problem.

  • Ejb-ql method help needed plz!

    Dear All,
    I get the following error: the details are given below!
    Unknown query: public abstract java.util.Collection com.sextanttech.entities.implementations.UserBean.ejbSelectUsers(int,int,int) throws javax.ejb.FinderException
    The relevant part of my ejb-jar.xml file
    <query>
    <query-method>
    <method-name>ejbSelectUsers</method-name>
    <method-params>
    <method-param>int</method-param>
    <method-param>int</method-param>
    <method-param>int</method-param>
    </method-params>
    </query-method>
    <ejb-ql><![CDATA[
    SELECT user.userName
    FROM UserTable user
    WHERE user.flag1 = ?1
    AND user.flag2 = ?2
    AND user.flag3 = ?3]]>
    </ejb-ql>
    </query>
    The relevant part of my entity bean class:
    public Collection getselectedusers() throws FinderException // this is my business method impl.
    Collection cc = this.ejbSelectUsers(1,1,1);
    return cc;
    public abstract Collection ejbSelectUsers( int flag1,int flag2,int flag3 ) throws FinderException;
    Thanks in advance!
    alex.

    hi buddy,
    select method cannot be declared in both home or remote interfaces...only in bean impl class
    and i did exactly that...plz notify me if u get any ideas.
    regards

  • Request dispatcher method--help needs

    Hi,
    I used request dispatcher method to redirect the from one servlet to another servlet.But when i use get method it is functioning well.
    But when i use post method it is giving error...
    I need to use post method...
    How can it possible..
    Thanks,
    Babu B

    you have code for request.RequestDispatcher.forward(""); method in both doPost and
    doGet methods for the servlet. However your initial form is not set with method
    to POST.
    By default the method is GET and it will execute code in doGet and not code in
    doPost() method. so in your first form use method as POST instead of keeping
    it to default i.e no method specified.
    let me know where are you using RequestDispatcher.
    //rohit

  • CD ripping (sort of) help need

    Hello all, I have a 20 gig Touch I bought mainly for transferring CD's to, but I have an irritating problem. Whenever I play a CD through the Touch software or Windows player I get a Kind of crackling sound that lasts for about 30 secs. which sounds similar to the start of a vinyl record. Obviously, this sound is then picked up if I rip the CD to transfer. This happens on brand new discs so I don't think my CD's are the problem and I don't get the crackling when I use a normal CD player. I have tried cleaning the CD's and the laser pick-up on my computer to no avail. Just wondered if anyone else who rips CD's as had this problem or if anyone else has any helpful suggestions that would be great!

    I think there's most likely just an issue with the CD-ROM digital audio extraction. The most likely cure will be getting a new CD-ROM, but it might also be an issue with the motherboard as well.
    It's difficult to know for sure unfortunately.

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

  • What types of sort performed by sort method of Array class ?

    I use normal bubble sort and method Array.sort() to sort some given data of an Array and then count the time.But Array.sort() method takes more time then normal bubble sort.
    Can anybody tell me what types of sort performed by sort method of Array class?

    I'm pretty sure that in eariler versions (1.2, 1.3
    maybe?) List.sort's docs said it used quicksort. Or I
    might be on crack.You are actually both correct, and wrong :)
    From the documentation of the sort methods hasn't changed in 1.2 -> 1.4 (as far as I can notice), and the documentation for sort(Object[]) says (taken from JDK 1.2 docs):
    "This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
    The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n*log(n) performance, and can approach linear performance on nearly sorted lists."
    So, how could you be correct? The documentation for e.g. sort(int[]) (and all other primities) says:
    "Sorts the specified array of ints into ascending numerical order. The sorting algorithm is a tuned quicksort, adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance."
    Your memory serves you well :)
    /Kaj

Maybe you are looking for

  • CFDocument and trouble converting to pdf

    Hello, I'm simply trying to convert a word doc to .pdf using CF9.  But when I try it, I get the following error... 500 - Internal server error. There is a problem with the resource you are looking for, and it cannot be displayed. Also, coldfusion ser

  • Non-Standard Time format

    SS2008 R2 I have to store and manipulate data from a new phone system.  Some of the columns are "Time" interval.  So while they behave like a SS "Time" data type they can hold a value greater than 24 hours (ex. 25:10:33) .  This causes SS to blow, of

  • Cross domain SSAS connection - NT Authority\Anonymous

    Hi Friends, We have a web service which is consumed by a web application. Two instances of the same web service (Same application pool) is deployed in the same box and one webservice connects to SSAS 2008 and another one connects to SSAS 2012.  The a

  • JavaFx For Mobile

    hi frndz i am new in JavaFX technology. Can u suggest me ,how i can develop mobile application by using JavaFx thanks in advance

  • Help! Info needed on how to qualify for Student Licence for CS4

    Hi, I'm after some info which I just can't seem to find on the web! Exactly what kind of student do you need to be to qualify for a Student Edition in the UK? Do you need to be doing a degree or can you just enroll on a part time course at a local co