comparing array values
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 8 of 8

Thread: comparing array values

  1. #1
    Join Date
    Nov 2008
    Posts
    20

    comparing array values

    Hi:

    I have an array with a number of values in it.
    I would like to re-order the array based on the values; from highest value to lowest value.
    What type of algorithm should I use for this?
    I am thinking that we need one loop to test every number in the array and another nested loop to test each number by all the other numbers; (including itself?).
    For example right now I have two arrays with the same data; but I need to compare/sort the values in one array and then update the both arrays with the correct order of the data. Should I make a new array to hold the temporary values?
    I am just lost with the algorithm; an example would be much appreciated!

  2. #2
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: comparing array values

    Use one of the sort methods provided in the Arrays class. If the items in the array have a natural ordering (e.g. Strings or numeric types) you just pass the array to the method and it will be sorted for you. If the items have no natural order, or must be sorted in a special order, you can write a Comparator that compares two items and returns an indication of their order. You can then pass this Comparator to the sort method along with the array, and it will be used to sort the items.

    Give us a shout if you get stuck.

    The cheapest, fastest, and most reliable components of a computer system are those that aren't there...
    G. Bell
    Please use [CODE]...your code here...[/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

  3. #3
    Join Date
    Nov 2008
    Posts
    20

    Re: comparing array values

    hey thanks for the reply.
    i have another method in another class which helps compare the two arrays and return different values based on whether they are the same, one is bigger, or smaller.
    I have come up with an algorithm to sort the array; but this algorithm only works if there are no repeat values in the array.
    Basically I am testing each value in the array against all the other values; and I count the number of values in the array which is greater than the value and I add one to that value. The position is thus determined for the value being compared.
    EX:
    Code:
    public class NewClass {
        public static void main(String[] args) {
            double[] list;
            list = new double[6];
            for(int a=0; a < 5; a++) {
                list[a] = Math.random();
            }
            for(int a=0; a < 5; a++) {
               System.out.println(list[a]);
            }
            double[] newList;
            newList = new double[6];
           for(int a = 0; a<5; a++) {
               int position=0;
               for(int b =0; b<5; b++) {
                   if(list[a] < list[b]) {
                       position++;
                   }
               }
               newList[position] = list[a];
           }
           System.out.println("Sorted output");
           for(int a=0;a<5;a++) {
               System.out.println(newList[a]);
           }
            
        }
    }
    But the above code is only functional if there are no repeat values in the array being compared.
    If there are repeat values; the algorithm fails because it will try to place the same number into the same position twice and thus will end up missing out on a position.
    How can I solve this problem?

  4. #4
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: comparing array values

    Quote Originally Posted by kk_kk View Post
    How can I solve this problem?
    Use the Arrays.sort(..) method. Don't reinvent the wheel.

    If you have two arrays with the same data (why?) and you want to sort them both, sort both with the Arrays.sort(..) method.

    If you have some problem with that, explain it fully.

    If there is some valid reason why you cannot use the Arrays method, implement a standard sort algorithm - a quick Google will turn up a variety of sort algorithms. You're wasting your time trying to write your own sort.

    Simplicity does not precede complexity, but follows it...
    A. Perlis
    Last edited by dlorde; November 27th, 2008 at 05:52 AM.
    Please use &#91;CODE]...your code here...&#91;/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

  5. #5
    Join Date
    Nov 2008
    Posts
    20

    Re: comparing array values

    Well the problem is that I do not know how to use the array-sorting functions with the type of data I am using.
    Right now my array is full of "ages" but these ages are string texts. But I have a method which actually compares two objects and returns values of (-1,0,1) based on the result. So I cannot directly sort the array right?
    My professor stresses that we should use that compareAge method in the method which I am having trouble on (selectionByAge). This method is basically used to reorder the array passed to it by the age of the objects in the array.
    I just cant really get a grasp of how to order all of the values after comparing them... I would love to use pre-existing functions; but how would I do that in my case?


    Thanks

  6. #6
    Join Date
    May 2006
    Location
    UK
    Posts
    4,474

    Re: comparing array values

    Well the problem is that I do not know how to use the array-sorting functions with the type of data I am using.
    Not knowing how to use a standard API is no excuse for wirting your own version. Have you tried looking at the Java Docs or reading tutorials.
    Right now my array is full of "ages" but these ages are string texts. But I have a method which actually compares two objects and returns values of (-1,0,1) based on the result. So I cannot directly sort the array right?
    Yes you can still use the Arrays.sort(..) method, provided you provide a java.util.Comparator object to handle the sorting.
    My professor stresses that we should use that compareAge method
    OK, so your Comparator object needs to call compareAge(..) to do the comparision.

  7. #7
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: comparing array values

    Seems a bit odd to have ages as Strings, but I guess there's a reason...

    If you have a method that will compare 2 objects and return -1, 0, or 1, then that's all you need to use the standard sort methods. That's the method that should provide the natural ordering of the objects (natural ordering is where the objects implement the Comparable interface by providing a compareTo method that returns -1, 0, or 1).

    As I already said, you can either use the basic Arrays.sort method and pass in an array of objects that are comparable, or you can use the extended sort method and pass in the array plus a Comparator.

    If you'd looked up the JavaDocs for Comparator, you'd have seen that it defines a method called compare, which takes two objects, compares them and returns -1, 0, or 1. Sound familiar?

    If your objects don't implement the compareTo method the way you want (which I guess they don't, being Strings), make a Comparator with your comparison method and pass it to the Arrays.sort method, something like this:
    Code:
    // create an age comparator
    Comparator<String> ageComparator = new Comparator<String>() {
       public int compare(String age1, String age2) {
          // your comparison that returns that returns -1, 0, or 1 here
          return result;
       }
    };
    
    // sort the age array using the age comparator
    Arrays.sort(myAgeArray, ageComparator);
    That's all there is to it.

    The process of preparing programs for a digital computer is especially attractive, not only because it can be economically and scientifically rewarding, but also because it can be an aesthetic experience much like composing poetry or music...
    D. Knuth
    Please use &#91;CODE]...your code here...&#91;/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

  8. #8
    Join Date
    Nov 2008
    Posts
    20

    Re: comparing array values

    Hey guys thanks for the help!
    I finally for it to work!
    Last edited by kk_kk; November 30th, 2008 at 02:46 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center