About the sort method of arrays

Hi,
I found that for primitive types such as int, float, etc., algorithm for sort is a tuned quicksort. However the algorithm for sorting an object array is a modified merge sort according to the java API. What is the purpose of using two different sorting strategy?
Thanks.

The language knows how to compare two ints, two doubles, etc. For Object arrays, however, it's not a simple matter of comparing two reference values as ints or longs. We're not comparing the references. We have to compare the objects, according to the class's compareTo() method (if it implements Comparable) or a provided Comparator. The size of an int is known, fixed, and small. The size of an object is unknown, variable, and essentially unbounded. I don't know for sure that that difference is what drove the different approaches, but it is a significant difference, and mergesort is better suited to use cases where we can't fit the entire array into memory at one time. It seems reasonable that we'd get better locality of reference (fewer cache misses, less need to page) with an array of ints than with an array of objects.
Edited by: jverd on Mar 18, 2011 3:16 AM

Similar Messages

  • 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

  • A question about the getProperty method defined in the Security class

    Hello Everyone!
    I would like to ask a question about the getProperty method defined in the
    Security class.
    public static String getProperty(String key) Do you know how can I exract the list of all possible keys?.
    Thanks in advance,

    I found the answer, in fact the keys are defined in the java.security file.

  • Why doesn't reflection reveal the clone() method in arrays?

    I was surprised to discover that the following code does not reveal the method "clone()", even though you can call "clone()" on an Object[]. Can anyone explain why this is? I was hoping to use the Reflect API to clone an arbitrary object if it was Cloneable, and to throw an Exception otherwise. How can I do this?
    import java.lang.reflect.Method;
    public class Test {
         public static void main(String[] args) throws Exception {
              Object x;
              //pick a class
              x = new Object[] {};
              //is it Cloneable?
              System.out.print("The class " + x.getClass().getCanonicalName() + " is ");
              if(!(x instanceof Cloneable)) System.out.print("NOT ");
              System.out.println("Cloneable");
              System.out.println("-------");
              //what methods are available?
              Method[] meths = x.getClass().getMethods();
              for(Method m : meths) {
                   System.out.println(m.getName());
              System.out.println("-------");
    }

    Just to clarify. I know that clone() is protected in Object, but it is certainly a public method in array objects such as int[], float[], Object[] etc. Test: call clone() on any of these objects! Also, I realize that Cloneable does not itself guarantee the method clone(). Nevertheless, if you take a regular Cloneable object, such as a String, then typically, if you ran myObject.getClass().getMethods() on that object, you'd find the method clone() in the resulting list. i.e., that Class has overwritten Object's protected clone() method with a public clone() method. So since int[], float[] and all the rest have a clearly public clone() method, then why doesn't myFloatArray.getClass().getMethods() show me a method called "clone"? I guess it would have to have something to do with the fact that arrays are funny kinds of classes that are not properly handled by the Reflection API, but is it on purpose that clone() isn't available?

  • About the tab "Method"  in definition of  activity

    In the tab "methods" in the definition of activity, what's meaning of Modal call and how to export paramaters and import parameters there.

    Try searching the SAP Help first for secondary methods in workflow. It is amazing how many answers are in there. And as an added bonus you also comply to the forum guidelines.
    Regards,
    Martin

  • About the setting method of  Instant Messaging(collabo4.01)

    Please teach me the setting method of Instant Messaging ID ( yahoo ).
    Although an icon is displayed, it will not be in an offline state.

    Hi,
    You can debug you JSPDynpage either from NWDS with the help of break points or by writing log statements in your code which will be written in defaultTrace log file.
    Check this to debug from NWDS:
    NetWeaver Portal Debugging
    Check this to write log statements:
    http://help.sap.com/saphelp_nw70/helpdata/EN/b0/003c41325fa831e10000000a1550b0/frameset.htm
    Netweaver Portal Log Configuration & Viewing (Part 3)
    Regards,
    Praveen Gudapati

  • About the biggest size of array

    I am writting a applet for big data management.
    I need a array such as
    pkeydata=new byte[(short)15000];
    Is it possible?
    I have been asked the technical support of oberthurcs,
    He give the answers:
    //=======================================================
    The applet isn't written in a standard way for JavaCards.
    An example is the allocoation of 15000 bytes of memory.
    I think you should rethink the applet design and no
    allocate memory like that.
    //=========================================================
    Is that true? If that is true ,could you tell me the biggest
    size of array I can allocat?
    TKS

    I am writting a applet for big data management.
    I need a array such as
    pkeydata=new byte[(short)15000];
    Is it possible?It should be possible. Here is a citation from the Javacard VM spec:
    2.2.4 Limitations of the Java Card Virtual Machine
    The limitations of resource-constrained hardware prevent Java Card programs from
    supporting the full range of functionality of certain Java platform features. The
    features in question are supported, but a particular virtual machine may limit the
    range of operation to less than that of the Java platform.
    To ensure a level of portability for application code, this section establishes a
    minimum required level for partial support of these language features.
    The limitations here are listed as maximums from the application programmer?s
    perspective. Applets that do not violate these maximum values can be converted
    into Java Card CAP files, and will be portable across all Java Card implementations.
    From the Java Card virtual machine implementer?s perspective, each maximum
    listed indicates a minimum level of support that will allow portability of applets.
    2.2.4.2 Objects
    Arrays
    Arrays can hold a maximum of 32767 fields. That means: if your applet's code and data requirements are within the given EEPROM range and the used card is specification compliant, the allocation of a byte-array holding 15000 elements should work.
    I have been asked the technical support of
    oberthurcs,
    He give the answers:
    //=====================================================
    The applet isn't written in a standard way for
    JavaCards.
    An example is the allocoation of 15000 bytes of
    memory.
    I think you should rethink the applet design and no
    allocate memory like that.
    //=====================================================
    [..]Afaik there are other card manufacturers e.g. Orga Card Systems, that are supporting the allocation of arrays in that way. Your kind of allocation as described above is according to the spec.
    Hope that helps
    Carsten

  • About the read() method; it returns an integer

    when I us the read method (from the filereader class) to read from a file , it retyrns an ASCII representation of the character.
    However , I can't display character on the screen like that (numbers). so, how can I turn them back to characters, so I can show them properly?
    Another Question: How can I set the position of components inside a panel. I don't like the way the layoutmanager sets their location. I want to do it myself
    Thanx

    so I can show them properly?Cast to char: System.out.print((char) inputCharacter);
    I want to do it myselfSet the layout manager to null and position the components with setBounds or setPosition and setSize. Good luck making it look right when the fonts and font sizes change or the container is resized.

  • I need suggestion about the way , method, or path of learning GUI

    Since there are many IDEs that are capable of developing the Java GUI quickly, one of my friend suggest me to learn GUI using code instead of drag and drop GUI component. He said when your boss ask you to fix the error/bug for the front-end part of the program, which is written in code only.
    Another situation is that when you are working with a team and your team members using code instead of these drag&drop, he said i have to adapt to using these code to write the GUI.
    Actually he has point. what do you guys think? please post your opinion.

    roadorange wrote:
    Since there are many IDEs that are capable of developing the Java GUI quickly, one of my friend suggest me to learn GUI using code instead of drag and drop GUI component. You should go through the Swing tutorial and perhaps the 2D demo that comes with the JDK. Look at the code, run the examples, step through it or whatever you want. But I personally don't think you get much (except a massive, lasting headache) from writing the code by hand.
    He said when your boss ask you to fix the error/bug for the front-end part of the program, which is written in code only.Huh?
    Another situation is that when you are working with a team and your team members using code instead of these drag&drop, he said i have to adapt to using these code to write the GUI.I'm starting to lose you here...
    Actually he has point. what do you guys think? please post your opinion.I say use the GUI tools (don't fight evolution)

  • About the setMode method of Camera

    Quoted from here:
    Sets the camera capture mode to the native mode that best meets the  specified requirements. If the camera does not have a native mode that  matches all the parameters you pass, Flash Player selects a capture mode  that most closely synthesizes the requested  mode. This manipulation may involve cropping the image and dropping  frames.
    Does it mean that the frames captured is not necessarily the same as required by setMode(width:int, height:int, fps:Number, favorArea:Boolean = true) ? The actual frame captured may be either wider/narrower,higher/lower in size and have higher/lower frequency than required ,is this true?

    It's going to depend on the camera and whether it supports what you have set. Nowadays drivers are pretty good and support all kinds of sizes and framerates. The flash will do it's best to give you what you want, but it all matters on whether or not the driver for the cam will support it.
    Graeme Bull
    www.fmsguru.com

  • Sorting Methods for an Array

    I'm trying to sort an object array of bank accounts based on their balance. JGRASP doesn't like my calling statement, which I don't think is correct.
    My question is am I calling the method correctly (trying to set the bankArray[counter].getBalance()) and am I using the sort method correctly?
    my call method
    bankArray = bankArray[counter].selectionSort(bankArray[counter].getBalance(), counter);My sort method:
    public static void selectionSort (double [] sort, int length)
    for (int i = length; i < 1; i--)
    double currentMax;
    int currentMaxIndex;
    currentMax = sort[0];
    currentMaxIndex = 0;
    for (int j = 1; j < i; j++)
    if (currentMax < sort[j])
    currentMax = sort[j];
    currentMaxIndex = j;
    }//End if
    }//End for

    There are some points to notice:
    Point 1: Your method receive an array of double and an int, as you passing a double and an int.
    Point 2: Your algorithm doesn't work properly. First of all, the selection sort works by selecting the smallest unsorted item remaining in the list, and then swapping it with the item in the next position to be filled. Also, note that you don't swap the array elements in any moment.
    Point 3: In Java, your selectionSort method don't need to receive a parameter to inform the array length. The array itself already have that information ("myArray.length").
    Point 4: About the call of your method, you made it as the selectionSort method returns an array of BankAccounts - Supposing that you represent a bank account through an BankAccount class and bankArray[i] is an array of [i]BankAccount objects. It's not true. As you can see, your selectionSort method returns void, or either, returns nothing.
    Observing those 4 first points, we can re-write your selectionSort method like this
         public static void selectionSort(double[] numbers) {
                for (int i = 0; i < numbers.length - 1; i++)
                  int minIndex = i;
                  for (int j = i + 1; j < numbers.length; j++)
                    if (numbers[j] < numbers[minIndex])
                      minIndex = j;
                  double temp = numbers;
              numbers[i] = numbers[minIndex];
              numbers[minIndex] = temp;
    Now, when I try to re-write the call, I noticed other important odd thing about your approach: The [i]selectionSort method was written to sort bankAccounts, but it receives an array of double values. Being thus, you must to previously create a double[] object filled with the accounts' balances and then sort it. But, once sorted, how can you return the balances to their proper account? There is no way to do it. You have to sort a bunch of BankAccount objects, instead of an array of balances...
    An intuitive implementation of this sorting cound be something like that:     public static void selectionSort(BankAccount[] accounts) {
              for (int i = 0; i < accounts.length - 1; i++) {
                   int minIndex = i;
                   for (int j = i + 1; j < accounts.length; j++) {
                        double
                             currBalance = accounts[j].getBalance(),
                             minBalance = accounts[minIndex].getBalance()                    
                        if (currBalance < minBalance)
                             minIndex = j;
                   BankAccount temp = accounts;
                   accounts[i] = accounts[minIndex];
                   accounts[minIndex] = temp;
    I noticed form your call that the [i]selectionSort method boleng to the BankAccount class. Once this method is static, It's strongly recomended that you invoke this method in a static way (from the class, instead of from an object).
    Here it goes a fictional BankAccount class and a TestBankAccount class. Read it, Run it, Study it, Understand it.
    package help.sun.imbrium;
    public class BankAccount {
         private double balance;
         private int number;
         public static void selectionSort(BankAccount[] accounts) {
              for (int i = 0; i < accounts.length - 1; i++) {
                   int minIndex = i;
                   for (int j = i + 1; j < accounts.length; j++) {
                        double
                             currBalance = accounts[j].getBalance(),
                             minBalance = accounts[minIndex].getBalance()                    
                        if (currBalance < minBalance)
                             minIndex = j;
                   BankAccount temp = accounts;
                   accounts[i] = accounts[minIndex];
                   accounts[minIndex] = temp;
         public BankAccount(int number, double balance) {
              this.balance = balance;
              this.number = number;
         public double getBalance() {
              return balance;
         public void setBalance(double balance) {
              this.balance = balance;
         public int getNumber() {
              return number;
         public void setNumber(int number) {
              this.number = number;
         public String toString(){
              return "[Account #" + number + " balance: $" + balance + "]";
    class TestBankAccount{
         public static void main(String[] args) {
              BankAccount[] accounts = {
                   new BankAccount(1, 154.23),
                   new BankAccount(2, 1554.23),
                   new BankAccount(3, 15.3),
                   new BankAccount(4, 854),
                   new BankAccount(5, -4.79),
              System.out.println("Unsorted:\n\t" + arrayToString(accounts, " "));
              BankAccount.selectionSort(accounts);
              System.out.println("Sorted:\n\t" + arrayToString(accounts, " "));
         private static String arrayToString(Object[] objs, String separator){
              StringBuilder sb = new StringBuilder();
              for (int i = 0; i < objs.length; i++) {
                   Object obj = objs[i];
                   sb.append(obj.toString());
                   if(i < objs.length - 1)
                        sb.append(separator);
              return sb.toString();

  • What are the preferred methods for backing up a cluster node bootdisk?

    Hi,
    I would like to use flarcreate to backup the bootdisks for each of the nodes in my cluster... but I cannot see this method mentioned in any cluster documentation...
    Has anybody used flash backups for cluster nodes before (and more importantly - successfully restored a cluster node from a flash image..?)
    Thanks very much,
    Trevor

    Hi, some backround on this - I need to patch some production cluster nodes, and obviously would like to backup the rootdisk of each node before doing this.
    What I really need is some advice about the best method to backup & patch my cluster node (with a recovery method also).
    The sun documentation for this says to use ufsdump, which i have used in the past - but will FLAR do the same job? - has anyone had experiance using FLAR to restore a cluster node?
    Or if someone has some other solutions for patching the nodes? - maybe offline my root mirror (SVM) - patch root disk - barring any major problems - online the mirror again??
    Cheers, Trevor

  • Can I adjust the sorting of Podcast as displayed on the IPOD itself

    Itunes by default sorts my podcast with the newest podcast at the top.
    If I want to redisplay the sorting within iTunes, I just click on the release date column and they re-sort with the oldest at the top. This doesn't change the way they sort in the ipod window. The ipod still displays the newest at the top.
    I'm just learning about the sort order field in itunes - info - sorting but I don't see how this can set up the change of date option as a permanent change to sort by date descending. Any advice or am I just trying to mess with my ipod too much.
    Thanks,
    Nyimbo

    Don't worry about messing with your ipod too much. It is probably the best way to learn about it.
    So far the best way I have found is to create a playlist, I usually use the same name as the podcast, sort the podcast by the release date, select all of them and add to the playlist. Then just play the podcast from the playlist.
    Someday Apple may wake up and realize people, their customers, would like to install podcasts onto their iPods in the same order they are in iTunes.

  • The problem about the signal of JNI

    Hello,
    When the system (it creates by the C language) created here is operated on Solaris and javaVM is operated using a JNI, the phenomenon which the core file outputs within the JIT compiler of java (libsunwjit.so) has occurred.
    Although it had generated twice until now, since it had collided with the signal which the signal has generated in one of the another threads, and it uses internally by JavaVM from the contents of a core file when it generated first, it had generated.
    However, although the core file was investigated when it generated at the 2nd times, there was no trace that another thread generated the signal.
    Is there any case where collide with the signal currently used by JavaVM, and also a signal is generated in a JIT compiler?
    What thing has an obstacle used as the factor which a JIT compiler makes have generated the signal in the past again?
    Please give me the reply to the above-mentioned question for a cause elucidation.
    As appending data, the contents which referred to the core file are described below.
    (gdb) thread 1
    [Switching to thread 1 (LWP    163        )]
    #0 0xfe359d88 in __sigprocmask () from /usr/lib/libthread.so.1
    #1 0xfe34eb34 in __sigredirect () from /usr/lib/libthread.so.1
    #2 0xfe351a10 in thrpkill_unlocked () from /usr/lib/libthread.so.1
    #3 0xfe239470 in abort () from /usr/lib/libc.so.1
    #4 0xfb49353c in panicHandler ()
    from /opt/fujitsu/jasmine/JasEMedia/jre/lib/sparc/classic/libjvm.so
    #5 0xfb798084 in intrDispatchMD ()
    from /opt/fujitsu/jasmine/JasEMedia/jre/lib/sparc/native_threads/libhpi.so
    #6 0xfe359348 in __libthread_segvhdlr () from /usr/lib/libthread.so.1
    #7 0xfe35bdf0 in __sighndlr () from /usr/lib/libthread.so.1
    #8 0xfe3586f8 in ?? () from /usr/lib/libthread.so.1
    #9 0xfb3bd8bc in JITPerformDynamicPatch ()
    from /opt/fujitsu/jasmine/JasEMedia/jre/lib/sparc/libsunwjit.so
    #10 0xfb3de848 in JITResolveConstPoolEntry ()
    from /opt/fujitsu/jasmine/JasEMedia/jre/lib/sparc/libsunwjit.so
    #11 0xb945908 in ?? ()
    #12 0xc5054e4 in ?? ()
    #13 0xe2974c in ?? ()
    #14 0x851b75c in ?? ()
    #15 0x7c3841c in ?? ()
    #16 0xb917560 in ?? ()
    #17 0x8a9b6d4 in ?? ()
    #18 0xb8e18e0 in ?? ()
    #19 0x71377d8 in ?? ()
    #20 0x7137784 in ?? ()
    #21 0x7d7d7f4 in ?? ()
    #22 0xc67c4b0 in ?? ()
    #23 0x913998c in ?? ()
    #24 0xb2bf58 in ?? ()
    #25 0xc51a854 in ?? ()
    #26 0x8794c7c in ?? ()
    #27 0xfb3de980 in JIT_INVOKER_MARKER ()
    from /opt/fujitsu/jasmine/JasEMedia/jre/lib/sparc/libsunwjit.so
    #28 0xfb494cec in notJavaInvocation ()
    from /opt/fujitsu/jasmine/JasEMedia/jre/lib/sparc/classic/libjvm.so
    #29 0xfb457674 in jni_Invoke ()
    from /opt/fujitsu/jasmine/JasEMedia/jre/lib/sparc/classic/libjvm.so
    #30 0xfb45930c in jni_CallVoidMethod ()
    from /opt/fujitsu/jasmine/JasEMedia/jre/lib/sparc/classic/libjvm.so
    #31 0xfbee0d7c in ChartJem_Generate ()
    from /opt/fujitsu/jasmine/EMImageChart/lib/GKM0JEMC.so
    #32 0xfb7630a4 in ?? ()
    from /opt/fujitsu/jasmine/data/default/methods/JasEMedia/lib043C.so.2.0
    #33 0xff2b106c in odb_OmsPcExec () from /opt/fujitsu/jasmine/lib/libjas.so
    Please contact me, if the core file is required. Separately, I will send.
    In that case, also about the transmission method, please unite and contact me.
    The system configuration is as follows.
    Operation System:SOLARIS(7)R00081
    Java version:1.2.2 Classic VM (build JDK-1.2.2-W, green threads, sunwjit)
    I'm hoping someone can help me out.
    Thanks!

    After that, a problem is not solved. Would you teach, if there is the method of something saying?

  • What about the "Foreach" of Java

    public class LotteryArray {
    * @param args
    * @param args
    public static void main(String[]args)
         final int MAX=10;
         int[][]odds=new int[MAX+1][];
         for(int n=0;n<=MAX;n++)
              odds[n]=new int[n+1];
         for(int n=0;n<odds.length;n++)
              for(int k=0;k<odds[n].length;k++)
                   int lotteryOdds=1;
                   for(int i=1;i<=k;i++)
                        lotteryOdds=lotteryOdds*(n-i+1)/i;
                   odds[n][k]=lotteryOdds;
         for(int[]row:odds)
              for(int odd:row)
                   System.out.printf("%4d", odd);
              System.out.println();
    }I don't Know about below
    for(int[]row:odds)
              for(int odd:row)
                   System.out.printf("%4d", odd);
              System.out.println();
         }if every element of odds will fill in row?
    and so the element of row will copy to odd?
    pls pay attention to odd dosn't equal odds

    okay,Got it
    Thanks
    but what i ask is about the Multidimensional ArraysA multidimensional array is just an array of arrays. I've never use the enhanced for loop with one, but I imagine it would be like this: // Old way
    int[][] arr = ...;
    for (int ix = 0; ix < arr.length; ix++) {
        int[] innerArray = arr[ix];
        for (int jx = 0; jx < innerArray.length; jx++) {
            int value = innerArray[jx];
            // do stuff with value
    // Enhanced for loop
    int[][] arr = ...;
    for (int[] innerArray : arr) {
        for (int value : innerArray) {
            // do stuff with value
    }

Maybe you are looking for

  • Greek characters in PDF output

    Hello All, We are running on 11.5.10.2. We have recently converted to WE8MSWIN1252 charset. After that reports server is crashing with below error when even we try to run a PDF report. Oracle Reports Server CGI - The Reports Server Engine terminated

  • Resetting a connection matched by ACL

    A requirement is to send a TCP Reset (RST) without changing ASA's global setting "service". The protocol for the connection is unknown. My understanding is that actions such as "reset", "drop" or "drop-connection" is for an "inspect" type Policy-Map

  • How to handle the our stock in logicistic service provide

    Hi, I have the scenio and how to config in SAP.Iam placing the PO to vendor, Vendor suply the raw material directly to our logistic service provider when ever we need we pull the stock ( consignment). The stock is in Service provide place.How to desi

  • V_V2 and V_R2 Replanning the orders

    Have looked into the transaction V_R2 and with this transaction we see how many orders and can evaluate the order stock for a special material. V_V2 is used to make the real replanning and it seems that this can only be used for orders not yet confir

  • SolMan BW Setup: Install Datasource not working - no datasources displayed

    Hi there, I am busy with new SolMan EHP1 SPS6 implementation and doing the Basic Settings > BW Setup in the IMG. The SolMan and BW client is the same (all on SolMan client 700), and I have done the General Settings. Moving to the BW-Based EWA Reporti