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;

Similar Messages

  • 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

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

  • How to convert an int array to string array?

    Hi,
    Can anyone please help me with this question?
    int number={4,6,45,3,2,77};
    I like to convert this into a list and sort
    List mylist = Arrays.asList(number);
    Collections.sort(mylist);
    But first I need to convert the int array to String array.
    Please advise. Thanks.

    If you want to convert your int array to a String array, you have no choice but doing a conversion element by element in a for loop.
    However, if the sort method doesn't behave as desired, you can use the one with 2 parameters, the second parameter being a comparator class.
    Check the javadoc for more information : http://java.sun.com/j2se/1.3/docs/api/java/util/Collections.html
    /Stephane

  • Question on int array

    Hi All,
    i want to find out the max.value,the next max.value and so on and so forth..
    for example :
    int iArr[] = {5,3,7};
    first i have to find out 7,then 5 and and 3..
    how to proceed?
    Thanks

    Hi "mkreddy123",
    If I understand you correctly, you want to sort an 'int' array in descending order.
    If this is correct, then I suggest using the "sort()" method in class "java.util.Arrays".
    I didn't see any mention (in your post) of the java version you are using, so I will assume you are using the latest version (1.4). Here is a link to the relevant javadoc:
    http://java.sun.com/j2se/1.4.1/docs/api/java/util/Arrays.html
    Of-course that sorts the array in ascending order. You then need to "reverse" the array in order to get descending order.
    [I'm assuming you _do_ know how to reverse an array -- in other words, make the last element in the array, the first element; make the second last element in the array the second element; and so on.]
    Hope this helps.
    Good Luck,
    Avi.

  • Returning int array from C to Java as method parameter

    Hello,
    I've been trying to accomplish this
    Java
    int[] myArray = ... (filled with some data);
    int retCode = myNativeCall(myArray);
    if(retCode == 0)
    doSomethingWith(myArray); //myArray gets overwritten with new data (with new size also) during the native call...
    C
    JNIEXPORT jint JNICALL Java_GenChav_rsaEncrypt(JNIEnv *env, jobject obj, jintArray myArray){
    jintArray outbuf;
    int[] new_array = .. // some function will fill this....
    int new_array_length = ...//some function will give me the new size, not big, 512 max...
    jint tmp[new_array_length]; //allocate..need something more ??
    memcpy(tmp, new_array, new_array_lenght);
    outbuf=(*env)->NewIntArray(env, new_array_length);
    (*env)->SetIntArrayRegion(env, outbuf, 0, new_array_length, tmp);
    myArray=outbuf;
    I tought this way I would have a updated myArray ints on the Java program...
    Any thought??

    user5945780 wrote:
    Ok, let's try to be constructive here...
    How I do implement a return type for my method like a int array ?First realized it has nothing to do with JNI. So the same question and answer applies to java only.
    >
    like:
    int[] return = myNativeCall();
    Yes.
    Then I will look for return[0], if it is == to 0, fine, it means a successful calculation by the native code. Not sure what that means. The structure of what you return it up to you.
    It can help when you are unsure of what to do in JNI....write a pseudo representation of what you want to do in a java method. Then translate that java method into JNI, everything in the pseudo method must be in the JNI code.

  • How do you invoke a method with native int array argument?

    Hi,
    Will someone help me to show me a few codes samples on how to invoke a method which has only one argument, an int [] array.
    For exampe:
    public void Method1(int [] intArray) {...};
    Here is some simple code fragment I used:
    Class<?> aClass = Class.forName("Test2");
    Class[] argTypes = new Class[] {int[].class};
    Method method = aClass.getDeclaredMethod("Method_1", argTypes);
    int [] intArray = new int[] {111, 222, 333};
    Object [] args = new Object[1];
    args[0] = Array.newInstance(int.class, intArray);
    method.invoke(aClass, args);I can compile without any error, but when runs, it died in the "invoke" statement with:
    Exception in thread "main" java.lang.IllegalArgumentException: object is not an instance of declaring class
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at Test1.invoke_Method_1(Test1.java:262)
         at Test1.start(Test1.java:33)
         at Test1.main(Test1.java:12)
    Any help is greatly appreciated!
    Jeff

    Sorry, my bad. I was able to invoke static methods and instance methods with all data types except native int, short, double and float, not sure the proper ways to declare them.
    After many frustrating hours, I posted the message for help, but at that time, my mind was so numb that I created a faulted example because I cut and pasted the static method invocation example to test the instance method passing int array argument.
    As your post suggested, "args[0] = intArray;", that works. Thanks!
    You know, I did tried passing the argument like that first, but because I was not declaring the type properly, I ended up messing up the actual passing as well as the instantiation step.
    I will honestly slap my hand three times.
    jml

  • Writing txt file to int array

    The project I was assigned is to write a program that takes numbers from a text file (all on one line, separated by spaces) and store them into a 5-element array. The program is supposed to check and see if the array is big enough to hold all the numbers from the text file, and if it isn't, it is supposed to double that array size. I've written the following code and it compiles, but it will not run due to this error:
    Exception in thread "main" java.lang.NullPointerException
         at java.io.Reader.<init>(Reader.java:61)
         at java.io.InputStreamReader.<init>(InputStreamReader.java:55)
         at ArrayReader.main(ArrayReader.java:16)
    ----jGRASP wedge2: exit code for process is 1.
    ----jGRASP: operation complete.
    This is what I have so far. If anyone could help me or point out anything I missed it would be greatly greatly appreciated.
    import java.io.*;
    public class ArrayReader
         public static void main(String[] args)
              File file = new File("numberlist.txt");
              FileInputStream fis = null;
              BufferedReader br = new BufferedReader (new InputStreamReader(fis));
              int i = 5;
              int x = 0;
              int[] array;
              array = new int;
              try
                   fis = new FileInputStream(file);
                   for (x = 0; x < array.length; x++)
                             if (x > array.length)
                                  i = i*2;
                                  System.out.println("Array too small. Doubling size to: " + i);
                             else
                                  array[i] = fis.read();
              catch(FileNotFoundException e)
                   System.out.println("File " + file.getAbsolutePath() +
                                            " could not be found on filesystem");
              catch(IOException ioe)     
                   System.out.println("Exception while reading the file" + ioe);
              for (i = 0; i < array.length; i++)
                   System.out.println(array[i]);

    ursusmajx wrote:
    Exception in thread "main" java.lang.NullPointerException
         at java.io.Reader.<init>(Reader.java:61)
         at java.io.InputStreamReader.<init>(InputStreamReader.java:55)
         at ArrayReader.main(ArrayReader.java:16)Start by looking at line 16 in ArrayReader.main. It's not lie 16 in the code you posted here, so either you haven't posted the code you tried to run or you're not running the code you think you are.
    I do see where you are using fis before assigning it a value.
    db

  • 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

  • How to pass int array as an IN parameter to PLSQL Procedure

    Hi,
    How to pass int array in java to a stored procedure througn jdbc
    and what type of data type I should declare to this IN parameter
    in PLSQL Procedure.
    Thanks,
    Simi

    Hi,
    The best way to do what you want depends on what you want.  Start by describing what you need to do.  It's best to post some sample data (CREATE TABLE and INSERT statments) and what results you want from that sample data.  (See the forum FAQ: https://forums.oracle.com/message/9362002)
    If you have ideas about how to do the job (e.g., populating a temporary table) it can be helpful to include those, too, but distinguish clearly between WHAT you need to do and HOW you might do it.
    As Bencol suggested, a SYS_REFCURSOR might be the best way to pass back the results.
    Since you didn't post your table, or even describe what you wanted to do with it, I'll illustrate using scott.emp, which is probably on your system.
    Say you wanted a procedure that took a DATE as an argument, and returned a some designated columns (empno, ename and hiredate in the example below) for all employees hired on or after the given DATE.  You might write a procedure like this:
    CREATE OR REPLACE PROCEDURE  hired_since
    (   start_date  IN   DATE
    ,   out_data    OUT  SYS_REFCURSOR
    AS
    BEGIN
        OPEN out_data FOR
            SELECT  empno, ename, hiredate
            FROM    scott.emp
            WHERE   hiredate  >= start_date;
    END  hired_since;
    SHOW ERRORS
    You can test it in SQL*Plus like this:
    VARIABLE   c REFCURSOR
    EXEC  hired_since (DATE '1982-01-01', :c);
    PRINT :c
    The output I got from this test was:
         EMPNO ENAME      HIREDATE
          7788 SCOTT      19-APR-87
          7876 ADAMS      23-MAY-87
          7934 MILLER     23-JAN-82

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

  • Problem with reading numbers from file into double int array...

    Okay, this is a snippet of my code:
    public void readMap(String file){
            try {
                URL url = getClass().getResource(file);
                System.out.println(url.getPath());
                BufferedReader in = new BufferedReader(new FileReader(url.getPath()));
                String str;
                String[] temp;
                int j=0;
                while ((str = in.readLine()) != null) {
                    temp = str.split(",");
                    for(int i=0;i<temp.length;i++){
                        map[j] = java.lang.Integer.parseInt(temp[i]);
    j++
    in.close();
    } catch (IOException e) {
    System.out.println("Error: "+ e.toString());
    map[][] is a double int array. Now, the code is running through each line of the text file (with each line looking like this: 0,3,6,2,2,3,1,5,2,3,5,2), and I want to put the numbers into a corresponding double int array (which is where map[][] comes in). Now, this code WOULD work, except I need to set the sizes of each array before I start adding, but I don't know how to get the exact sizes.. how can I get around this issue?
    Message was edited by:
    maxfarrar

    You can do a two-dimensional ArrayList? That syntax
    you wrote didn't work.
    I tried doing:
    private ArrayList<ArrayList><Integer>> map;
    Your syntax is just wrong -- or, this forum software has bug in handling angle brackets.
    ArrayList<ArrayList<Integer>>...The closing angle bracket after the second 'ArrayList' is the one generated by the bug. Basically, it should be T<T<T2>> without spaces. Oh, for that matter:
    Arraylist<ArrayList<Integer>>

  • 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

Maybe you are looking for

  • Iphone 5 not working- Past year warranty

    Hello, So I got my iphone 5 more than a year ago... I also have insurance on it through my carrier. It just isnt charging and I have no idea why. Its not the charger because I've tried on several different chargers that work with everyone else's phon

  • J2EE JNDI-00009 EJB Reference "ejb/SessionEJBCalled" could not be resolved

    When load (run) the following EJB (JDev 10.1.3.1.0 embedded server) loads with no problem: package project2; import javax.ejb.Stateless; @Stateless public class SessionEJBCalledBean implements SessionEJBCalledLocal { public SessionEJBCalledBean() {  

  • HT1688 my notes are deleting by themselves. What's going on?

    Just recently my notes on my iphone 4s have been deleting not all of them at once but so far about 4 or 5 have been deleted. What can I do to retrieve them? They are very important to me. 

  • Early Watch Report - Archive EWA

    Hello,   I have configured Early Watch Report in my Solution Manager 4.0 on Windows Server 2003 4 weeks back. EWA report is comng perfectly  but in my Solution for each server I am able to see only 2 (Latest one and  Next Schedued) EWA report at a ti

  • Tlf Bug Discussion

    We are facing some problem with new TLF framework. We need to add component(any UI component) in selected textflow. But we cant do that.  We need any UI element  like flow element (just like inlinegraphicElement for images) for UI components. Please