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

Similar Messages

  • Is there a better way to sort mail folders?

    Is there a way to sort mail folders the way I want them rather than alphabetical?

    Sumo23 wrote:
    Is there a way to sort mail folders the way I want them rather than alphabetical?
    no.

  • Simpler way to sort 2-d string array?

    I have a long 2d string array, and I would like to sort by the 2nd value. It originates as:
        public static final String names[][] = {
         {"000000", "Black"},
         {"000080", "Navy Blue"},
         {"0000C8", "Dark Blue"},
         {"0000FF", "Blue"},
            {"000741", "Stratos"},
         {"FFFFF0", "Ivory"},
         {"FFFFFF", "White"}
        };As you can see, they are pre-sorted by the hex values. That is useful for part of the app.
    There are 1,567 entries. I would like to alphabetize the color names and place them in a list widget. I need to keep the associated hex color values with the name values. All I can think of to do something like:
    1) make a temporary long 1-d string array
    2) fill it by loop that appends the hex values to the name values: temp[i] = new String (names[1] + names[i][0])
    3) sort temp[] with built in Java sort
    4) make a permanent new string array, hexValues[] for the hex values
    5) copy the last 6 characters of each item to hexValues[]
    6) truncate the last 6 characters of each item in temp[]
    7) build list widget with temp[]
    Is there a more elegant way? What I'd really like to do is build a 1-d array of int's, with the values representing the alphabetized locations of the names. However, I don't see any built-in which would do that kind of indirect sort.
    Second question -- Can the backgrounds of each item in a list widget be a different color? Ideally the list would show the color name in black or white, and the its color value as background. Specifically, I'm trying to build the list accomplished by the Javascript code here:
    * http://chir.ag/projects/name-that-color/
    and add it to my Java interactive color wheel:
    * http://r0k.us/graphics/SIHwheel.html
    BTW, I have converted his name that color Javascript (ntc.js) to a native Java class. It is freely distributable, and I host it here:
    * http://r0k.us/source/ntc.java
    -- Rich
    Edited by: RichF on Oct 7, 2010 7:04 PM
    Silly forum software; I can't see what made it go italic at the word new.

    I am implementing a sort infrastructure along the lines of camickr's working example, above. Part of my problem is that I am new to both lists and collections. I've tried searching, and I cannot figure out why the compiler doesn't like my "new":
    public class colorName implements Comparable<colorName>
        String     name, hex;
        int          hsi;
        static List<colorName> colorNames;
        public colorName(String name, String hex)
         float     hsb[] = {0f, 0f, 0f};
         int     rgb[] = {0, 0, 0};
         int     h, s, b;     // b for brightness, same as i
         this.name = name;
         this.hex  = hex;
         // Now we need to calculate hsi,
         this.hsi = (h << 10) + (s << 6) + b;  //  hhhhhhssssiiiiii
        ***   findColorName() performs 3 functions.  First, it
        *** will auto-initialize itself if necessary.  Second,
        *** it will perform 3 sorts:
        ***   -3) byHSI:  sort by HSI and return first element of sorted list
        ***   -2) byNAME: sort by name and return first element of list
        ***   -1) byHEX:  (re)reads ntc.names, which is already sorted by HEX;
        ***               returns first element of list
        *** Third, on 0 or greater, will return the nth element of list
        *** Note: ntc.init() need not have been called.
        public colorName findColorName(int which)
         if (which < -3)  which = -3;
         if (which >= ntc.names.length)  which = ntc.names.length - 1;
         if (which == -1)  colorNames = null;     // free up for garbage collection
         if (colorNames == null)
         {   // (re)create list
             colorNames = new ArrayList<colorName>(ntc.names.length);
             for (int i = 0; i < ntc.names.length; i++)
                 colorNames.add(new colorName(ntc.names[1], ntc.names[0]));
            if (which == -1)  return(colorNames.get(0));
    }On compilation, I receive:
    D:\progming\java\ntc>javac colorName.java
    colorName.java:117: cannot find symbol
    symbol  : constructor colorName(java.lang.String[],java.lang.String[])
    location: class colorName
                    colorNames.add(new colorName(ntc.names[1], ntc.names[0]));
                                   ^
    1 errorLine 117 is the second-to-last executable line in code block. I know it is finding the ntc.names[][] array the ntc.class file. I had forgotten to compile ntc.java, and there were other errors, such as in line 115 where it couldn't find ntc.names.length. Compare camickr's two lines:
              List<Person> people = new ArrayList<Person>();
              people.add( new Person("Homer", 38) );As far as I can tell, I'm doing exactly the same thing. If you have any other feedback, feel free to make it. The full source may be found at:
    * http://r0k.us/rock/Junk/colorName.java
    PS1: I know I don't need the parenthesis in my return's. It's an old habit, and they look funny to me without them.
    PS2: My original design had the "static List<colorName> colorNames;" line defined within the findColorName() method. The compiler did not like that; it appears to be that one cannot have static variables within methods. Anyway, that's why I don't have separate sorting and getting methods. I'm learning; "static" does not mean, "keep this baby around". Its meaning is, "there is only one of these babies per class".
    -- Rich

  • Sorting  on 2D  Int Array

    Guys
    I have 2D Array of Type Int , Can some body Please explain me HOW to Apply the SORT options on the
    1st Coloum ONLY with simple Example....
    int a[ ][ ] = {  {5,10}, {4,20}, {3,15}, {2,25} };
    Thx
    Karthik

    Hi rkippen. Are you there? I'm trying to understand your piece of code that show how to sort a 2D array. I'm trying to do the same thing. If you could offer any more explanation I would appreciate it. Please respond to [email protected] Thanks
    java.util.Arrays.sort(a, new Comparator() {
         public void equals(Object o) {
              return o == this;
         public int compare(Object o1, Object o2) {
              int[] a1 = (int[]) o1;
              int[] a2 = (int[]) o2;
              if (a1[0] < a2[0]) return -1;
              if (a1[0] > a2[0]) return 1;
              return 0;

  • A Better Way to do Multi-Camera

    I am able to do multi-camera edits, synchonization and playback but I suspect I am doing it inefficiently.  All of the tutorials I've seen start with only the clips that will participate in the multi-cam ALONE in a sequence.  And I know all the steps from there.  But what I don't know is how to efficiently proceed if there are may clips in a sequence and I only want to do multi-cam on one stack of clips in the sequence.  For instance, let's say that I have 10 clips on the timeline.  All are on video and audio tracks 1.  But the 6th clip also has multi-cam clips on video and audio tracks 2-4.  What I currently do is
    1. copy  these clips (only the clips located in the 6th spot tracks 1-4 on the timeline but not the entire sequence)
    2. paste them to a new sequence (sequence #2)
    3. create another new sequence (sequence #3)
    4. drag sequence #2 into sequence #3)
    I know all the multi-cam steps after this.
    The question is: is this the most efficient way to do this when I'm starting with a sequence that has clips on them other than the ones that I want to participate in multi-cam.  I'm creating 2 new sequences to accomplish this.  Can it be done in only one new sequence?

    I edit a lot of things the same way you are talking about when you have many clips on video 1 and then just a few where there are mulitple cameras.
    If there are only 2 shots (Video 1 and Video 2) here is what I do.
    1.  Line up Video 2 over top of Video 1 in the proper place.
    2.  Right click on the clip in Video 2 and select "Unlink"  (Unlinking will unlink the audio and video.  You do this so that when you cut video 2 you do not also cut the audio)
    3.  Place the CTI so that it is on your Video 2 Clip and then double click on that clip.  This will open the clip in your Source Monitor.
    4.  BEFORE moving the CTI, Right Click on the tab of your Program Monitor and select "Gang Source and Program".
    5.  Now turn off the eyeball on Video 2
    6.  When you scrub through the timeline you will see both your video in both the Program and Source monitors moving.  Unfortuantely you cannot just play the video and watch both.  You can play it and watch the Program monitor and when you stop the Source monitor will catch up.
    7.  Use the Cut tool to cut out spots of Video 2 so you can see Video 1.
    8.  One tip is that if you are going to cut the very first part of Video 2 the best thing to do is to get the CTI where you want Video 2 to start and then use your selection tool to just trim it to that spot.  If you cut it and delete it you will loos your video in the source monitor.  Not that big of a deal because all you have to do is Double Click on it again and re-select Gange Source and Program, but it saves you from having to mess with it.
    If I have 3 or more video clips I just highlight them all and right click and select "Nest".  That will make your new sequence for you with all your clips you selected.  Just then do a normal Multi Cam edit.
    Hope this helps some!
    Phil

  • Best way to sort (short of dragging each one)

    With so many apps, sorthing them into a working order one-by-one is a bear, especially across multiple pages - many times the app stops on a page and I can't get it to go to the next page, then apps get displaced and it causes changes on another page and so on and so on...
    Is there a better way to sort, maybe a master list of some sort, that I can access to set them in the order I want them to appear?

    No such option exists - at the present time anyway.
    You can use this link to provide Apple your feedback regarding this.
    http://www.apple.com/feedback/iphone.html

  • Is there a better way to add int arrays together?

    I'm working on a project that will add arrays of integer together...all element are nonnegative integers
    For example
    A = [0 1 2 3]
    I need to find an algorithm to find 2A= A + A, 3A = A+A+A....., hA = A +...A ( h times)
    For 2A, the result array will look like this
    2A = [ 0 1 2 3 1 2 3 4 2 3 4 5 3 4 5 6]
    Then using Array.sort(2A) i will have 2A= [ 0 1 1 2 2 2 3 3 3 3 4 4 4 5 5 6].
    Lastly I will write another code to get rid of repetitions to get the desired array 2A = [ 0 1 2 3 4 5 6]
    public static int[] hA(int[] a, int h){
       // mon = null;
       //mon = MonitorFactory.start("myFirstMonitor");
           if (h==1) return a;
           if (h==2){          
                  int[] b = new int[(a.length)*(a.length)];
               int count = 0;
               int maxa = a.length,maxb=b.length;
               for (int i = 0 ; i < maxa; i++)
               for (int j=0 ; j <maxa; j++)
                 b[count]=a[i]+a[j];
                    count++;
                return b;
               else
               return hA(a,h-1);     
           }I still don't know how to write recursive code to get it to find 3A, 4A....hA....
    is there any better way to do this?

    sorry for not defining it better
    2A ={ a + a' | a,a' E A}
    that means for A = { 0 1 3} , 2A ={ 0 1 2 3 4 6}
    but to get to [ 0 1 2 3 4 6], i don't know of any better way to achieve it.
    Also to find 3A = { a+a'+a'' |a,a',a'' E A}
    that means for A = { 0 1 3} ,3A={ 0 1 2 3 4 5 6 7 9}
    the idea is simple but to put into java code is not...at least for me

  • Array cycling - a better way?

    Is there a better way of doing this? I use this a lot, and feel there must be a better way, but don't know what. gridSize is an array that contains x and y dimensions. Some code needs to be executed for each square on the grid. I was once told that avoiding refering to arrays explicitly (i.e. ar[2]) is a good way to go, but I can't figure out how to do that in this instance!
    for (int i = 0; i < gridSize[0]; i++) {
    for (int j = 0; j < gridSize[1]; j++) {
    //...code...
    }

    Yeah, I don't think you mean to use gridSize[0], but length. Still, you shouldn't need to specify it like ar[2], keep it a variable. This is how you could loop through every square:for(int i = 0; i < gridSize.length; i++)
        for(int j = 0; j < gridSize.length; j++)
    //...code...
    }Just note that the <i> is really [i] because of a forum software bug.

  • Have you got a better idea? Is there a better way? ( arrays )

    Hello!
    First post here and ofcourse it is a question I hopo you people don't mind. I will get right to the point:
    I have a picture , or to be precise the pixels of a picture stored as a 3 dimensional array in the form of
    img[y][x][color].
    Since I am working on grayscale the color doesn't matter , so de facto I have a 2dim array of X-Y coordinates. For my programm ( a line tracker of sorts) I need to be able to select a subgroup of this array. This subgroup should be equivalent to a small (appr. 10x20 pixels wide) box in the original picture. My problem is that this box could be at any angle, that is it's side do not have to run parallel to the x-y-Axis.
    Now how would be the best way of doing this?
    My idea is to calculate the lines of the rectangle geometricaly and then try to approximate them onto the array. After that I can use them as boundaries to select every pixel that is inside the box.
    Is there a better way? Does somebody have any experience with something similar?
    Any help would be greatly appreciated...
    Alexis

    Two things to try. Try rebuilding the mailbox. This can take awhile if you have a lot of mail.
    Rebuild mailbox
    Try reindexing the mailbox. This can take awhile if you have a lot of mail.
    Reindex messages

  • A better way to Re-Order the Sort in Pivot view ?

    Hello,
    Question first- Is there a better way to do this?
    Background- Have a simple pivot table w/ requirements to put the Status column in order that makes sense to the business not alphabetical.
    Example, # of Service Req with Status needs to be listed as Assigned, Accepted, Completed, Closed, Re-assigned.
    My solution was to create a column iin table view, use a CASE statement to say when Accepted =1 etc. I then sorted ASC, hid the column in table view and then pivot view I added Status column and hid the new CASE column. I am getting the results I expected but I was wondering if there was a better way to do this?
    Thanks- Neally

    As far as the Presentation Layer is concernd (i.e., in Answers) your way is the best I can think of. The only way you can sort a list of values apart from a way the system could automatically determine (e.g., alphabetically, chronologically, numerically, etc.) is to create your own definition. Without human intervention or customized rules, there is no way any system would know that "C" should come before "S" (as in "Assigned" and "Accepted", or that "O" should come before "L" as in "Completed" and "Closed").
    Since the system knows how to order numbers (e.g., 1,2,3, etc.), it makes sense to create your "rule" (using your CASE statement) to assign each status level to the appropriate "number" in the sequence.
    That's what I would do. The only addition I can add is you could do this in the rpd by adding an "order" column to your LOVs in the table and exposing that as a column in the Presentation Layer. Then you can use that order column as the sort.

  • How do I find the total number of elements in a multi dim array

    How do I find the total number of elements in a single or multi dim array?
    For example, a 2x3 array has 6 elements, and a 2x3x4 has 24. How do I compute this very easily - is there a single VI that does this?
    David
    Solved!
    Go to Solution.

    Use "array size" (array palette) followed by "multiply array elements" (numeric palette)
    (Works also equally well for 3D arrays and higher)
    For a 1D array, just use "array size".
    Message Edited by altenbach on 02-05-2009 05:57 PM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    NumberOfElements.png ‏3 KB

  • Multi-plot Graphs, is there a better way?

    I am still not good at graphs in LabView but I think I am making some programs and I can usually get a graph to show with I want it to show with only a few hours of dinking around with it...
    Anyway using graphs certainly makes for messy code unless there is a better way to wire this. Basically this graph shows four temperature probes and is updated every minute. Every 15 minutes a check for stabilization is run. Seemingly the only way I have been able to get multiple plots with Time as the X-Axis is to use an X-Y chart, but I have to index my readings out individually and put each in it's own shift register, and add it to the graph separately.
    There must be a better way?
    Solved!
    Go to Solution.
    Attachments:
    G2.jpg ‏258 KB

    I think part of your problem is you are not aware of the "concatenate inputs" option for build array. You don't need multiple build arrays for the array of clusters you are wiring into the graph (pink wire). Just expand the build array, wire in all your clusters, then right click the build array and choose "concatenate inputs". Next, you can use a cluster to store all your graph arrays (orange wires) which will greatly clean up your diagram.
    CLA, LabVIEW Versions 2010-2013

  • External Multi Way Merge Sort in Java!

    Hi guys,
    some month ago I've sent [this post|http://forums.sun.com/thread.jspa?forumID=31&threadID=5310310] to the Java Programming Forum to notify the availability of an External Multi Way Merge Sort written in Java, tuned and tested over GB of text data and under LGPL license, that can help you in dealing with huge logs or CVS files.
    I want here just to notify you about this implementation.
    You can run the sorting algo via command line or you can call from any Java class instantiating the ExternalSort class, setting its properties, and calling run().
    Searching in the forum I saw many people that ask for an help in sorting huge textual files that doesn't fit in memory. My post solve this problem, but I think that very few people are aware of it :( ....
    Hope to help who need this feature. See you!

    Nice work this SmallText,
    did not try it, but like the idea
    I have been doing something similar in c (long, long time ago) and what made our compression really tight for typical csv files was decision to build one huffman coder for each field. The trick was to include field separator symbol into static huffman coder for every field, that provides you with End Of Field signal where to switch to next decoder.
    for ExternalSort, I would suggest to make it multithreaded. Having so many many cores and low prices of ram today, it makes a lot sense. Easy way to do it is to have IO_Thread(s) and Worker_Threads (the first ones do read and write and second ones are for sorting).... this is powerfull as you utilize many cores and can easily extend some processing (like compression, token frequency counting or whatever...) via callbacks in each phase (chunking/sorting/merging)
    again, congrats, really nice work

  • Better way for inserting column into array?

    I have to insert a 2-D array(20x10) into the end (column) of a bigger 2-D array(1000x10). I am seeing two ways to do that:
    1. Insert smaller 2D array at the end of bigger array.
    2. Insert the bigger array at the 0th column of smaller array.
    Which one would be more efficient? Will there be any performance difference?
    Or any other better way to do this?
    The second one looks simpler but I think it would require a bigger copying of memory.

    Both methods use a buffer allocation, so they might be very similar. Since we don't know what the compiler is doing, you could also try this:
    I am assumung that you only need to append once and not append more and more columns as the program progresses. Is this correct? In any case, you should consider operating on the transposed version, because it is always easier to append rows instead of columns (rows are adjacent in memory, while appending columns require more data shuffling under the hood
    In any case, you should simply wire up the alternatives and do a proper benchmark if you are planning to use this on much larger arrays in the future, for example. Can you give us some context how you are planning to use this?
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    AppendColumns.png ‏3 KB

  • Best way to make a 2 dim byte array

    I have a byte array of 16384 bytes but i want to make
    a 2 dimensional array with a size of 256*64 out of it,
    what is the best way to do this?

    A simple way is to use the "Reshape Array" function (Functions>Array>Reshape Array).
    =====================================================
    Fading out. " ... J. Arthur Rank on gong."
    Attachments:
    Reshape_array.gif ‏3 KB

Maybe you are looking for