Java - Sorting an array (ascending, descending)

You can easily sort an Array using Arrays.sort(). It doesn`t matter if the contents of the array are Integers or Strings.

By default, Comparable is implemented for objects. sort() sorts an array in ascending or descending order by comparing the values returned by Comparable.

Lets learn how to use Arrays.sort()` by implementing the following.

  • sort int array sort int array (ascending, descending)
  • int array, partial integer
  • String array
  • String array, ordered by character length
  • object array

Sort int array (ascending, descending)

I have an array of ints as below. If you pass this array as an argument to Arrays.sort(), it sorts in ascending order. Since the order of the variable arr is changed inside the sort() function, there is no need to assign it to arr separately.

int[] arr = {1, 26, 17, 25, 99, 44, 303};

Arrays.sort(arr);

System.out.println("Sorted arr[] : " + Arrays.toString(arr));

Output:

Sorted arr[] : [1, 17, 25, 26, 44, 99, 303]

Sort descending

To sort in descending order, you must pass Collections.reverseOrder() in addition to the argument of Collections.reverseOrder().

Integer[] arr = {1, 26, 17, 25, 99, 44, 303};

Arrays.sort(arr, Collections.reverseOrder());

System.out.println("Sorted arr[] : " + Arrays.toString(arr));

Output:

Sorted arr[] : [303, 99, 44, 26, 25, 17, 1]

In fact, Collections.reverseOrder() is a Comparator object. You have to implement Comparator yourself, but since descending order is frequently used, Collections provides it by default.

If you want to implement your own descending comparator you can do something like this:

Integer[] arr = {1, 26, 17, 25, 99, 44, 303};

Arrays.sort(arr, new Comparator<Integer>() {
    @Override
    public int compare(Integer i1, Integer i2) {
        return i2 - i1;
    }
});

System.out.println("Sorted arr[] : " + Arrays.toString(arr));

The code above can be implemented in this shorter way using Lambda.

Integer[] arr = {1, 26, 17, 25, 99, 44, 303};

Arrays.sort(arr, (i1, i2) -> i2 - i1);

System.out.println("Sorted arr[] : " + Arrays.toString(arr));

When comparing with Comparator, you should use Integer, not int.

int array, partial sort

The above example sorts the entire array. However, it is also possible to sort only part of an array.

You must specify the range to be sorted by passing the first index and the last index as arguments to sort() as follows. The code below passes 0 and 4 as arguments, which means to sort only the arrays containing index 0 to index 4.

int[] arr = {1, 26, 17, 25, 99, 44, 303};

Arrays.sort(arr, 0, 4);

System.out.println("Sorted arr[] : " + Arrays.toString(arr));

Output:

Sorted arr[] : [1, 17, 25, 26, 99, 44, 303]

String array sorting

String arrays are also equivalent to Integers.

If implemented as below, sorting is done by comparing the ASCII values of the alphabet.

String[] arr = {"Apple", "Kiwi", "Orange", "Banana", "Watermelon", "Cherry"};

Arrays.sort(arr);

System.out.println("Sorted arr[] : " + Arrays.toString(arr));

Output:

Sorted arr[] : [Apple, Banana, Cherry, Kiwi, Orange, Watermelon]

Sorting in descending order is the same as in the example above.

String[] arr = {"Apple", "Kiwi", "Orange", "Banana", "Watermelon", "Cherry"};

Arrays.sort(arr, Collections.reverseOrder());

System.out.println("Sorted arr[] : " + Arrays.toString(arr));

Output:

Sorted arr[] : [Watermelon, Orange, Kiwi, Cherry, Banana, Apple]

String array, sort by string length order (Sorting)

There are times when you want to sort by string length order. In this case, you have to implement Comparator yourself.

You can implement a Comparator that compares string lengths like this:

String[] arr = {"Apple", "Kiwi", "Orange", "Banana", "Watermelon", "Cherry"};

Arrays.sort(arr, new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        return s1.length() - s2.length();
    }
});

System.out.println("Sorted arr[] : " + Arrays.toString(arr));

Ouput:

Sorted arr[] : [Kiwi, Apple, Orange, Banana, Cherry, Watermelon]

You can also use Lambda to implement more concisely like below.

String[] arr = {"Apple", "Kiwi", "Orange", "Banana", "Watermelon", "Cherry"};

Arrays.sort(arr, (s1, s2) -> s1.length() - s2.length());

System.out.println("Sorted arr[] : " + Arrays.toString(arr));

Sorting an array of objects

Arrays containing objects can also be sorted. In this case, you need to implement Comparable in your class to make it comparable.

I have created a class called Fruit as follows: This class is Comparable ` is implemented.

public static class Fruit implements Comparable<Fruit> {
    private String name;
    private int price;
    public Fruit(String name, int price) {
        this.name = name;
        this.price = price;
    }

    @Override
    public String toString() {
        return "{name: " + name + ", price: " + price + "}";
    }

    @Override
    public int compareTo(@NotNull Fruit fruit) {
        return this.price - fruit.price;
    }
}

In the above class, Comparable compares its own class and the price of Fruit passed as an argument.

Now you can sort the Fruit array with sort() like this:

Fruit[] arr = {
        new Fruit("Apple", 100),
        new Fruit("Kiwi", 500),
        new Fruit("Orange", 200),
        new Fruit("Banana", 50),
        new Fruit("Watermelon", 880),
        new Fruit("Cherry", 10)
};

Arrays.sort(arr);

System.out.println("Sorted arr[] : " + Arrays.toString(arr));

Output:

Sorted arr[] : [{name: Cherry, price: 10}, {name: Banana, price: 50}, {name: Apple, price: 100}, {name: Orange, price: 200}, {name: Kiwi, price: 500}, {name: Watermelon, price: 880}]

If you look at the results, you can see that they are sorted in ascending order.

Since Comparable was implemented inside the class, sort() was able to compare this object to other objects. And since Comparable is implemented to compare in ascending order, Fruit objects can be sorted in ascending order.

Reference

codechachaCopyright ©2019 codechacha