Results 1 to 15 of 15
  1. #1
    dan0 is offline Member
    Join Date
    Feb 2009
    Posts
    40
    Rep Power
    0

    Question [SOLVED] Sorting array in descending order?

    What is the best way to convert an int array from ascending order to descending order?

    For example, how can I convert exArray1.1 to exArray1.2?

    (exArray1.1)
    example[0] = 1
    example[1] = 2
    example[2] = 3
    --------------
    (exArray1.2)
    example[0] = 3
    example[1] = 2
    example[2] = 1

  2. #2
    angryboy's Avatar
    angryboy is offline Senior Member
    Join Date
    Jan 2009
    Posts
    742
    Rep Power
    6

    Default

    is the array already sorted and you want to reverse it? or do you have to sort then reverse?
    USE CODE TAGS--> [CODE]...[/CODE]
    Get NotePad++ (free)

  3. #3
    emceenugget is offline Senior Member
    Join Date
    Sep 2008
    Posts
    564
    Rep Power
    7

    Default

    just reverse it. it's not hard to do.

  4. #4
    dan0 is offline Member
    Join Date
    Feb 2009
    Posts
    40
    Rep Power
    0

    Default

    Quote Originally Posted by angryboy View Post
    is the array already sorted and you want to reverse it? or do you have to sort then reverse?
    The array is already sorted, and I want to reverse it. I put the following code together to sort it in descending order, but there has to be a better way, right?

    Java Code:
            private int[] descendSort(int[] array){
    		int[] tempArray = new int[array.length];
    		for (int i = array.length-1; i <= 0; --i){
    			for (int j = 0; j < array.length-1; ++i){
    				tempArray[j] = array[i];
    			}
    		}
    		return tempArray;
    	}

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    You don't want to use nested for loops here, trust me. Try to figure out what this would do on paper with an array of 3 items. No, much better is to use a single for loop, and figure out how to use "i" and the array length so that you'll get a proper index for the second array.

    Java Code:
      private int[] descendSort(int[] array)
      {
        int[] tempArray = new int[array.length];
    
        for (int i = 0; i < tempArray.length; i++)
        {
          // int j = some function of i and tempArray.length;
          tempArray[j] = array[i];
        }
        return tempArray;
      }
    Last edited by Fubarable; 03-11-2009 at 08:03 PM.

  6. #6
    dan0 is offline Member
    Join Date
    Feb 2009
    Posts
    40
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    No, much better is to use a single for loop, and figure out how to use "i" and the array length so that you'll get a proper index for the second array.
    Thanks for the help. The function I used to find "j" was:
    Java Code:
    (array.length-1)-i
    After inserting the above function, the method properly sorted in descending order.

    Lastly, Arrays don't have a reverse method like Collections do, right?

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Very good, and you're welcome. I didn't know whether Arrays had this method or not, so I looked it up in the API.

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    But collections can be used if the array holds objects:
    Java Code:
      public static void main(String[] args)
      {
        String[] stringArray =
        { "1", "2", "3", "4", "5", "6" };
        System.out.println(Arrays.toString(stringArray));
        List<String> stringList = Arrays.asList(stringArray);
        Collections.reverse(stringList);
        String[] stringArray2 = stringList.toArray(new String[0]);
        System.out.println(Arrays.toString(stringArray2));
      }

  9. #9
    dan0 is offline Member
    Join Date
    Feb 2009
    Posts
    40
    Rep Power
    0

    Default

    I too went through the API and was a bit surprised that Arrays didn't have something similar to Collection's reverse method... I thought I may have missed it.

    I appreciate the example of using Collection's reverse method, if the array holds objects.

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    I too was a bit surprised. Perhaps there is some deep reason having to do with an array being allowed to hold primitives, but again, I don't know.

  11. #11
    glhansen is offline Member
    Join Date
    Mar 2009
    Posts
    20
    Rep Power
    0

    Default

    If you want a general solution to sorting things as you please, you can use the Comparable interface. You need to define a method, compareTo(), which determines whether an item should be placed before or after another item. It seems like a lot of code below to set up and demonstrate it (and I'm not saying I've done it in a particularly economical way, either), but in my own experiments I've made a class with a number of different fields, and methods that set flags for which field to sort on, and whether ascending or descending. Maybe there's something useful here for you.

    import java.util.*;

    public class Sorter implements Comparable<Sorter> {

    private static Boolean ascending = true;
    int number;

    Sorter(int n) {
    number = n;
    }

    public int compareTo(Sorter temp) {
    int i;

    if (this.number > temp.number)
    i = 1;
    else if (this.number < temp.number)
    i = -1;
    else i = 0;

    if (ascending == false)
    i = -i;
    return i;
    }

    public void set(int n) {number = n;}
    public int get() {return number;}
    public static void sortAscending() {ascending = true;}
    public static void sortDescending() {ascending = false;}

    public static void main(String[] args) {
    ArrayList<Sorter> l = new ArrayList<Sorter>();
    for (int i = 0; i < 5; i++)
    l.add(new Sorter(i));

    System.out.println("Original order:");
    int i = l.size();
    int j = 0;
    while (j < i) {
    System.out.println(l.get(j).get());
    j++;
    }
    System.out.println("\n");

    System.out.println("Descending order:");
    Sorter.sortDescending();
    Collections.sort(l);
    j = 0;
    while (j < i) {
    System.out.println(l.get(j).get());
    j++;
    }
    }
    }

  12. #12
    vijay24805 is offline Member
    Join Date
    Mar 2009
    Posts
    15
    Rep Power
    0

    Default

    In compareto(object 1,obect 2) and compare() method the object ar comapared and returned -ve,0 and +ve values based on the comparision --- if object1 is greater than object 2 return 0,my question in what sense the object ar compared as greater or smaller?is it the no. of characters counted and compared?

    ex-obj1 let be "fun"
    and obj2 let be "hello" then if we compare this two object by using overriding of
    compare(obj1,obj2)
    {
    return obj1.compareTo(obj2);
    }
    how i can preddict wether it is -1,1 or zero?

  13. #13
    glhansen is offline Member
    Join Date
    Mar 2009
    Posts
    20
    Rep Power
    0

    Default

    Strings already have a compareTo function. The relevant documentation is here.

    Ah, heck. I can't post links because I only have 18 posts. Do a Google search on java strings.

    "a value less than 0 if the argument is a string lexicographically greater than this string"

    If you want to roll your own with a class that implements Comparable, docs are here.

    (Do a Google search on java comparable.)

    Specifically, "Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object."

    I have to be honest, I can never remember if it should be positive or negative. And, of course, it reverses if you use this.compareTo(input) or input.compareTo(this). I always resort to testing it and changing the sign if I have to.

    As a point of interest, by writing your own compareTo function you can make complex comparisons between multi-field objects. The only use I've done with it is sorting, and when a class implements Comparable and has a compareTo method, you automatically get sort(). I've made classes with static variables that specify which field gets sorted on first, and which second. To use, set the sort flags, then call Collections.sort(myObjectArray). The objects in the array are of a class that implements Comparable, not the array. You can stick them in any container class.

  14. #14
    vijay24805 is offline Member
    Join Date
    Mar 2009
    Posts
    15
    Rep Power
    0

    Default

    COULD YOU EXPLAIN HOW THAT REVERSE THING WORKS?
    HOW DOES THE this.compareTo(input) DO REVERSE SORTING?

    ReSortComparator rs = new ReSortComparator(); // #3
    Arrays.sort(sa,rs);
    for(String s : sa)
    static class ReSortComparator
    implements Comparator<String>
    {
    public int compare(String a, String b)
    {
    return b.compareTo(a);
    }

    HERE IN THE CODE Arrays.sort(sa,rs); WHAT IS THE VALUE OF rs? WHEN I EXECUTED THIS PART OF CODE I GOT THE ARRAY SORTED IN REVERSE ORDER.WHAT VALUE WAS ASSIGNED TO rs AND HOW DID IT HELPED THE METHOD Arrays.sort(sa,rs) TO SORT THE ARRAY IN REVERSE ORDER,THIS IS MY DOUBT?

  15. #15
    glhansen is offline Member
    Join Date
    Mar 2009
    Posts
    20
    Rep Power
    0

    Default

    Java knows how to sort primitives, but it doesn't know how to sort whatever arbitrary class that you define. So when you implement Comparable you need to write a compareTo method for your class, which returns a number less than zero if "this" is less than, or comes before, the input parameter, greater than zero if it comes after, and zero if they're the same.

    The class doesn't do the sorting, and the compareTo method doesn't do the sorting. Rather, the Java class, Collections, does the sorting. Put your set of objects in a container, like an ArrayList, and tell Collections to sort the container. Collections will call the compareTo method, which you have to supply for that class, to determine which objects come before other objects, and then it will shuffle the container and sort them. And it's your compareTo method that you can define any way you like, so that's how you can control the sort order. I've used static variables in the class, with methods to set them, and the compareTo checks those variable to determine which object comes first.

Similar Threads

  1. How to sort array objects into alphabetical order...
    By lisalala in forum New To Java
    Replies: 5
    Last Post: 03-03-2009, 11:01 AM
  2. Sorting in descending order
    By santanu in forum New To Java
    Replies: 6
    Last Post: 11-26-2008, 11:43 PM
  3. Descending order
    By santanu in forum New To Java
    Replies: 1
    Last Post: 11-04-2008, 04:33 PM
  4. Display the data in Descending order
    By santanu in forum New To Java
    Replies: 2
    Last Post: 10-31-2008, 12:06 PM
  5. Sorting an array of Strings
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-15-2008, 07:39 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
  •