Using .sort() to sort an array of numbers NOT as strings

Hi,
is there a function or simple way to sort an array of numbers in order of their values and not as strings? E.g, have 100 come AFTER 9; (9, 100) not (100, 9).
Thanks.

use the ARRAY.numeric parameter.
(and you can always use a custom sort function parameter for more customized sorts.)

Similar Messages

  • Sorting array of numbers

    I have an multiple arrays of numbers 1-10 in different orders. I want to sort them in ascending order.
    example
    for(int pass=0; pass < sizeofarray; pass++){
        for(int t=0; t < sizeofarray; t++){
            if(array[t] > array[t+1]){
                hold=array[t];
                array[t] = array[t+1];
                array[t+1] = hold;
    }This loops through 10 times no matter how the array is originally sorted. How do I decrease the number of times this cycles if the array is pre-sorted?
    example arrays {10,9,8,7,6,5,4,3,2,1} need to go 10 times
    {1,2,3,4,5,6,7,8,9,10} only needs to check it once.
    Help, please only loops, no array.sort. This is a homework assignment.

    Quicksort while effective, is not what I needed. A modified bubble sort is what I wanted. Thanks to all who posted. I found the logic I was able to modify for my needs at
    http://www.autoobjects.com/Home/Teaching/CmpE_126/CmpE_126_Lectures/Sortings/sortings.html#Bubble_Sort
    here's basically what it did (in C++):
        Improved Bubble Sort                                                                                                        */
    void BubbleSort( UserData x[ ], int siz ){
            int i, j, switched;
            /* outer loop controls the number of pass */
            for( i = 0, switched = true; i < siz - 1 && switched == true; i++ ){
                    /* initially no interchanges have been made on this pass */
                    /* inner loop controls each individual pass */
                    for( j = siz - 1, switched = false; j > i; j-- ){
                            if( getKey( x[ j ] ) > getKey( x[ j - 1 ] )){  /* an interchange becomes required */
                                    switched = true;
                                    Swap( x[ j ], x[ j - 1 ] );
                            }        /* inner loop */
                    }       /* outer loop */
            return;
            }Thanks to jbish who had the most useful answer for my needs.

  • Sorting an array of numbers with loops

    Hi, i'm looking for a way to sort an array or numbers with loops.
    my array looks like this. int[] numbers = {5,2,7,9,1}
    i know how to use the "sort" method and i want to do it without the sort method, but i am not very clear on the logic behind it.
    by the end it should look like this, {1,2,5,7,9}
    i know 2 loops are used, can you please give me a logic to work with.
    i have started the loops but what to do inside???
    int temp;
    for (int i=0; i<numbers.length; i++){
    for (int j=1; j<numbers; j++){
    if (numbers<numbers[j])
    temp = numbers[i];
    Any suggestions i will be thankful for.
    thank you.

    fly wrote:
    no not really a homework question.. i want to improve my logic because it is very poor at the moment.. but i'm sure someone knows how to sort an array with loops only.Yes, we do know how to do it, I once wrote a heapsort in assembly code, as a real work project. But you rarely get a project like that the good ones were all done years ago.
    All the algorithms I suggested you look at use loops. the simplest and slowest is the bubble sort. This one runs by comparing values and swapping their locations, the wikipedia article http://en.wikipedia.org/wiki/Bubble_sort has the algorithm.

  • Sort two one dimensional arrays

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

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

  • Sort Second Element in Array of Strict Type Def Clusters

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

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

  • Is it possible to sort rows by font color in Numbers ?

    Is it possible to sort rows by font color in Numbers ?

    CC,
    You probably had something in mind when you applied the colors to the text. It's always best to record the conditions directly rather than to indicate them indirectly by by use of color.
    You can use Conditional Formatting to do some color coding based on the condition. You might even find that it's easier to let the conditional format tool than to assign the colors manually.
    Jerry

  • Best algorithm to sort semi-sorted arrays?

    I am trying my hand at the hutter prize (http://prize.hutter1.net/)
    My current compression algorithm sorts an array of Comparable Objects every main cycle.
    -This array of objects can potentically increase by one object per cycle.
    -Each object's comparision value can change per cycle, however its order is mostly kept.
    This means that the over all order of the objects are similar between cycles.
    Is there an sorting algorithm which can take advantage of the semi-sorted state of the array?
    I was using the default Arrays.sort() however it does not seem to make much use of the semi-sorted input array and is too slow for my use.
    In order to speed up the sorting i have relaxed the need to be in strict order. I.e there can be some objects out of order.
    To this end I have developed a BucketSort which i thought should speed up the sorting however it seems to have the opposite effect!
    Is there any reason why this implementation is quite slow? (three times as slow as Array.sort() )
       private static int MAX_BUCKET=65535;
       private static Word[] buckets=new Word[MAX_BUCKET];
       public static void bucketSortReverse (Word[] a, int n)
            int i;
            int count=1;
            int index;
            Word curr;
            // fill up the buckets with the input words
            for (i=0;i<n;i++)
                 curr=a;
              index=(int) (curr.probablility*MAX_BUCKET);
              curr.next=buckets[index];
              buckets[index]=curr;
         // iterate over the buckets and construct the sorted words
         for (i=0;i<MAX_BUCKET;i++)
              curr=buckets[i];
              if (curr!=null)
                   while (curr!=null)
                        a[n-count++]=curr;
                        curr=curr.next;
                   buckets[i]=null;
    NOTE Currently my input Word array contains a maximum of 6000 words.
    Lowering the number of bins reduces the accuraccy of the sort and does not provide much increase in speed :(
    I have found some Open Source code which by default performs very similarly to Arrays.sort in terms of speed and have modified it to be non-strict in its ordering.
    This modified sorting algothim is approximately 15% faster but is still really not fast enough.
    By reducing the strict ordering of the sorting algorithm i have also reduced the level of compression. Ultimately i would like to have a fast sorting algothrim which takes into acount semi-sorted objects with out reducing strictness of the sort.
    Any ideas?

    Tree removal takes O(logn) and insertion takes O(logn). Compare this to an array where potentially a large number of elements need to be shifted O(n).
    Usually it takes hundreds of thousands of elements to notice a difference. So if your data is relatively small, then it may not be worth trying to optimize it.
    test of the parent may need to be performed to determine The balanced binary tree (TreeSet) that comes with the JDK doesn't allow access to the internal structure of the tree, so testing the parent isn't available. Even if it was, it would still take an O(logn) lookup to find the node and get its parent, so it wouldn't be a significant improvement.

  • Sorting a two dimensional array

    Hello!
    I have a twodimensional array that consists of 6 other arrays
    (like array[0 to 5][0 to 4]). The [4] of each sub-array is a index
    number that i'd like to use for sorting the array[0][x] to
    array[5][x] according to their array[x][4]-value. How would I do
    that?
    Thanks!

    use a custom sort function. check the sort() method of the
    array class for sample coding.

  • Numbers not sorting date/time correctly

    I would be grateful if someone can chime in - it's very simple thing and maybe I'm overlooking something.
    I have 3 columns:
    DATE - DESCRIPTION - TIME
    I need to sort them out by date, then by time.
    It works only for date cells - upon inspection I have noticed that time cells have creation date stamp as well which messes sorting up.
    Any suggestions ?
    Sorting like this works fine in Excel.

    Hi Alex,
    As has been stated (or implied) above, every every date and/or time displayed in Numbers is a Date and Time value marking a specific instant in time.
    Values that have been entered as date only (eg. October 1, 2012) mark the instant that day begins (eg. October 1, 2012 00:00:00).
    Values that have been entered as time only mark that instant on the day on which the entry was made (or in cases such as pop-up menu items, the day on which the item was created as a menu item).
    Values that have been entered as full Date and Time values mark the date and time that was entered.
    Here are three possible approaches to sorting your table 'correctly':
    Enter the Date and Time as a single and complete Date and time value (see example above), using a single column for these entries.
    OR
    Add a column containing a formula that extracts the time value from the Date and Time values in column C of your example table, then do the two-stage sort on your Date column then the new column as described in your initial post. See example below.
    Before sorting:
    After sorting (as indicated in Reorganize pane):
    OR
    Format your "Time" column as Text. Enter all "Time"s in 24 hour format (00:00 to 23:59), and use the two-stage sort you describe.
    Each of these will sort correctly using Numbers as it is supplied. Should you think Numbers shoud stop supporting ISO 8601, the International Standard for the representation of dates and times, the most effective place to make that recommendation would be via the Feedback channel. Use the Provide Numbers Feedback menu item in the Numbers menu (in Numbers) to request this change.
    Regards,
    Barry
    Regards,
    Barry

  • Sorting a 2-D array

    Hello Every one,
                            Can any one please help me out in sorting a 2-D array. Here is the requirement there will be some groups, and each group consists of 'x' number of elements.The user enters only elements but in a zig zag order. And the program short sort out each channel and list out to which group it is belonging (Where the 2-D array of Group name and elements is provided).
    Say for example if there are three groups with some elements in each groups as follows.
    Physics: retarder, force,torque,capacity
    Chemistry: reaction, chemicals, sodium
    Geography: land,map,soil, earth.
    And if the user enters the following input's: soil, torque, chemical, force,reaction, land.
    The program should return the following output:
    Note : The order of the elements should match the order they are defined.
    Physics, force,torque                                    ------------ group name and group elements in the first row
    Chemistry, reaction, chemical                        ------------ group name and group elements in the Second row
    Geography,land, soil                                    ------------ group name and group elements in the third row
    Thanks for the help
    - Raghu
    Solved!
    Go to Solution.

    Sure Jim, I can definitely share my project details.Here is what we are trying to achieve.
    The attached vi is used to transmit the messages to Engine ECM. It takes the input's *.dbc file where the channel names are defined
    The present vi is working like this. It transmit messages correctly only if the messages are defined in the ascending order(the order in which they are defined in the *.dbc file).
    Say for example take 3 PGNS
    1) 18ff0fef Which has the following channels in the PGN
    a) Notch
    b) Gear
    c) Service brake
    2) 14ff2ef which has the following channels in the PGN
    a) Bus_voltage
    b) Bus_current
    c) power
    3)14ff03ef which has the following channels in the PGN
    a) Coolant_temp
    b) oil_press
    c) Imat
    If I want to transmit the following channels and define them in the following order
    1) Gear
    2) Imat
    3) Bus_voltage
    4) Notch
    The program is only writing correct data for Gear,Imat and some garbage values for Bus_voltage and Notch.
    But if I define the channels in the ascending order as defined in the *.dbc file in the following fashion
    1)Notch
    2)Gear
    3)Bus_voltage
    4)Imat
    I can transmit the right data for each channel.
    So what Iam trying to do is Iam planning to sort out all the channels names what user enter's and sort the channels in the  order as defined in the *.dbc file and pass it to the program.
    And the other issue I am facing is if two channels belong to the same PGN like Gear and Notch I have to transmit the values in the same array.
    Say for example i want to transmit the values as follows Notch =4; Gear = 3; Bus_voltage = 25; Imat = 80 the array matrix will be like this
    Array_1: 4,3
    Array_2: 25
    Array_3: 80.
    I was able to sort out all the channels listed in the *.dbc file in to single array but have no clue how to do the rest of work. Can you please help me in achieving the expected result. Iam attaching the vi and picture which describes where channel information and channel values are passed to the program.
    Thank you,
    - Raghu
    Attachments:
    Output.vi ‏27 KB
    TX_GUI.PNG ‏77 KB

  • Sort a 2-dim array?

    Hello!
    Now we have the following problem: We need to sort a 2-dim array depending on the values in the first column. Then we need the corresponding row to move to the right place too... we send a VI so you can see an example of how it might look like. So we need (in this case) the first column to sort so we get 1,2 and 3 and so on, so the last row should be 3,4, 392 and 2047.
    We think this might be easy to solve but we need some tip :-) Thank you and best regards.
    Attachments:
    sortarray.vi ‏17 KB

    I wrote my own 2D string array sort routine. It has come in handy many times. You can enter the column number that you want to sort on, and the entire rows are rearranged in the order of the column sort. If your array is numeric, you can easily change the vi to use numerics instead. One day I hope to make it polymorphic. Here it is:
    - tbob
    Inventor of the WORM Global
    Attachments:
    Sort2DArray(str).vi ‏63 KB

  • How to sort a 2 dim Array ?

    hello
    I would like to sort a 2-dim array of double ( double[][])
    according to the 1st column
    It is possible to sort a 1st dim array (doubel[]) , but the method sort
    of the class Array doesn't work with double[][]).
    I have two (bad) solutions.
    1) Writing a sorting method but I would prefer using the sort' method of java which uses quicksort
    2) Creating a table of objects that implements Comparable but this would decrease performance
    Do you have a better Idea ?
    Thanks a lot

    I would like to sort a 2-dim array of double (double[][]) according to the 1st column
    Which is the first "column"? double[0][x] or
    double[x][0]?
    If it's the second one things get simple: your
    double[][] is really an array of objects where each
    object is an array of doubles. So all you need to do
    is write a custom Comparator for double[] to use the
    sort method:
    compare(Object obj1, Object obj2) {
    double[] d1 = (double[]) obj1;
    double[] d2 = (double[]) obj2;
    return d1[0] > d2[0];
    }Thanks for your so prompt answer.
    I can manage to put the data so that I sort the array according to x as in double[x][0]?
    But WHERE do I have to write the "compare" method ?
    Thanks

  • Better way to sort multi dim int array

    I'm tracking key value pairs of ints. I know that the keys will not repeat. I've decided to do this in an int[][] array
    int[][] data = new int[2][many millions]This app crunches a lot of data so I'm shooting for the best memory handling. I push a bunch of key - value pairs into the array. I will likely populate many if not all data and not have to search until I'm done populating so I'm not sorting as I go.
    I know that I can sort the single dim array data[0] but how can I keep the values array data[1] synchronized? I've tried a few things, all have been successful but I'm wondering if there's a better method. Currently I create copy arrays for the keys and values, sort the original keys, and loop through the copy keys. For each copy key I binary search the sorted keys and drop the value in the correct spot. I don't like having to allocate 2X the amount of memory for the swap arrays. Any thoughts?
    Thanks
    ST

    Jos, thanks for the reply. I tried this method but I don't get as much
    storage since each internal array counts as an object.Yes I know; maybe I've got something for you, waidaminnit <dig-dig/>
    <shuffle-shuffle/> Ah, got it. Suppose you wrap your two dim array in
    a simple class that implements this interface:public interface Sortable {
         public int length();
         public int compare(int i, int j);
         public void swap(int i, int j);
    }I think the semantics of the methods are obvious. Given this interface
    you can sort anything you like using this thingy:public class HeapSort {
         private Sortable s;
         private void heapify(int i, int n) {
              for (int r, l= (i<<1)+1; l < n; i= l, l= (i<<1)+1) {
                   if ((r= l+1) < n && s.compare(l, r) < 0) l= r;
                   if (s.compare(i, l) < 0) s.swap(i, l);
         private void phase1() {
              for (int n= s.length(), i= n/2; i >= 0; i--)
                   heapify(i, n);
         private void phase2() {
              for (int n= s.length(); --n > 0; ) {
                   s.swap(0, n);
                   heapify(0, n);
         public HeapSort(Sortable s) { this.s= s; }
         public Sortable sort() {
              phase1();
              phase2();
              return s;
    }kind regards,
    Jos

  • What is the Collation Used in ?sort:......?

    Hi,
    What is the default collation sequence of Publisher when doing sorting using the <?sort:...?> tag? My machines are configured "US English" as the locale, and my BI Publisher user (i.e. Administrator) is configured to run in "US English" as well.
    Here is the problem:
    BIP Sorting on Alphanumeric fields: alphabets come first followed by numerals:
    DDJ6A
    DDZ6B
    DD17U
    DD28W
    Actually I'm migrating reports from Siebel Actuate, in which: numerals comes before alphabets:
    DD17U
    DD28W
    DDJ6A
    DDZ6B
    which is consistent to ASCII or Unicode code point collation.
    Is there any way that I can configure BI Publisher so the ASCII(or Unicode code point) collation is retained. I think this is important as a large number of customers are migrating from Actuate and Crystal reports into BI Publisher.
    Thanks in advance,
    Jonathan

    Thanks, Vetsrini for your prompt reply.
    I finally use this workaround: I used an XSL tag in place of the <?sort:....?> tag after the <?for-each:...?> tag, in which I have an option of which language I'd like to base on for the sorting, as follows:
    <?sort:current-group()/ssOfficeCode;lang='la';'ascending';data-type='text'?>
    By trial and error, I've put in the lang="la" attributes so to use the Latin language (instead of English) for sorting, which will place numerals before alphabets.
    Best regards,
    Jonathan

  • Only on tempfile used during sql sorts

    environment : Entreprise 92010/W2K
    My temp tablespace (locally managed and temporary) has 3 tempfile, each with autoextend and maxsize limit.
    When i create an index on a big table, my 3 tempfile are used.
    But when a big sort occurs during a sql statement, only one tempfile is used and i get an ora-1652.
    Why all tempfiles are not used during sorts statements (union, max...) ?
    This behavior can be easily tested :
    - create a new temp ts with 3 small tempfile, autoextend on but very small maxsize
    - alter the user who will do the sorts
    - log on as user altered
    - create an index on a big table => the 3 tempfiles will grow
    - execute a query (max, min, union ,distinct...) => only one tempfile is used.
    SQL sort always done in only one file or bug ?
    Jean-Fran�ois L�guillier

    The 3 tempfile belong to the same ts.
    This ts is the temporary ts for my user which executes the sort sql statement.
    During execution, i monitor size of the 3 files (from v$tempfile) : only one was used during query and when it reached maxsize, i got ora 1652 but fres space were available in the 2 others tempfile.
    When i create a big index, i see changes in bytes for all tempfiles (in v$tempfile).
    One of my customer has same problem. He added tempfile to his temp ts but sort statement failed again.
    I tested this behavior with 92010/EE with W2K.
    I think it's a bug but nothing appears in patchset 9204.

Maybe you are looking for