Defocused lights

How to sort arrays in Java

If you need to sort some array of data in Java programming language, then this tutorial may be useful. There are various options available that can help you to get the desired result. For example, you can use the standard sort() method. Also, you can implement your own custom sorting function. Each option has advantages and disadvantages. Please review the following sections to get more details.

Using the Arrays.sort() method

The Arrays class provides the sort() method that allows you to sort data in Java applications. The usage is very simple. You just have to pass at least a single argument. There must be an array that you would like to sort.

Please review the following code sample. There, we create a simple array of numbers and then sort it by using the Arrays.sort() method.

The array is printed to the console with help of the Arrays.toString() method. It allows you to correctly print the contents of an array.

import java.util.Arrays;

class sample {
    public static void main(String args[]) {
        int[] listOfNumbers = {37, 29, 123, 32, 15, 83, 22, 41, 83, 17};

        Arrays.sort(listOfNumbers);

        System.out.println(Arrays.toString(listOfNumbers));
    }
}

If you run the given code, the console output should be like the following. As you may notice, the numbers are sorted there.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[15, 17, 22, 29, 32, 37, 41, 83, 83, 123]

Sorting a subset of an array

You can also sort a specific part of a given array. For that purpose, you have to pass two additional arguments into the sort() method. The second argument is the index of the first element that must be sorted. And the third argument is the index of the last element of the subset. It is worth mentioning that the last element is not included in the range.

Now, you can see the code that shows how to sort a subset of an array.

import java.util.Arrays;

class sample {
    public static void main(String args[]) {
        int[] listOfNumbers = {37, 29, 123, 32, 15, 83, 22, 41, 83, 17};

        Arrays.sort(listOfNumbers, 2, 8);

        System.out.println(Arrays.toString(listOfNumbers));
    }
}

The console output may be like the following. As you may notice, the first and last two numbers remain in the same positions.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[37, 29, 15, 22, 32, 41, 83, 123, 83, 17]

Sorting in a reversed order

The sort() method also allows you to sort data in a reversed order. To do that, you have to import the Collections class into your project. Then you have to use the reverseOrder() comparator to specify that the data must be sorted in a descending order.

The following code demonstrates how it should be done correctly.

import java.util.Arrays;
import java.util.Collections;

class sample {
    public static void main(String args[]) {
        Integer[] listOfNumbers = {37, 29, 123, 32, 15, 83, 22, 41, 83, 17};

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

        System.out.println(Arrays.toString(listOfNumbers));
    }
}

Please pay attention that we use the Integer type in the code. That's because the reverseOrder() comparator works only with arrays of objects. Also, following is the output of the given code sample.

eveloper@developer-pc:~/samples/java$ javac ./sample.java && java sample
[123, 83, 83, 41, 37, 32, 29, 22, 17, 15]

Sorting an array of strings

If you need to sort an array of strings, then you may use the Arrays.sort() method as well. The usage is exactly the same as you would sort an array of numbers.

Below, you can see the listOfStrings array that contains a list of strings. Then, we sort and print that array to the console.

import java.util.Arrays;

class sample {
    public static void main(String args[]) {
        String[] listOfStrings = {"red", "green", "blue", "white", "pink"};

        Arrays.sort(listOfStrings);

        System.out.println(Arrays.toString(listOfStrings));
    }
}

The output of the given code will be like the following. As you can see, the string values are sorted in an alphabetical order.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[blue, green, pink, red, white]

Sorting an array of strings in a reversed order

In addition, you may also sort the array of strings in a reversed order. For that purpose, you have to import the Collections class into the project. Then, you should use the reverseOrder() comparator in the code.

import java.util.Arrays;
import java.util.Collections;

class sample {
    public static void main(String args[]) {
        String[] listOfStrings = {"red", "green", "blue", "white", "pink"};

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

        System.out.println(Arrays.toString(listOfStrings));
    }
}

If you run the given code, the console will contain a list of strings which is sorted in a reversed order.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[white, red, pink, green, blue]

Sorting an array of objects

In the previous sections, we've described how to sort a simple array of objects or primitives. However, the Java language also allows you to sort an array of custom objects. But to do that, we have to define the special compareTo() method. It performs the actual comparison of the objects.

Please see the following code, it shows how this can be done. That Apple class implements the Comparable interface. Also, the toString() method was added to that class. It will print correctly the contents of the object to the console.

import java.util.Arrays;

class Apple implements Comparable<Apple>{
    private int size;
    private int weight;

    public Apple(int size, int weight) {
        this.size = size;
        this.weight = weight;
    }

    @Override
    public int compareTo(Apple apple) {
        return this.size - apple.size;
    }

    @Override
    public String toString() {
        return String.format("Apple (%d, %d)", this.size, this.weight);
    }
}

class sample {
    public static void main(String args[]) {
        Apple[] listOfApples = {
            new Apple(5, 8),
            new Apple(10, 7),
            new Apple(11, 5),
            new Apple(8, 10),
            new Apple(7, 9)
        };

        Arrays.sort(listOfApples);

        System.out.println(Arrays.toString(listOfApples));
    }
}

Now, you may try to run the given code sample. The console output should be like the following.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[Apple (5, 8), Apple (7, 9), Apple (8, 10), Apple (10, 7), Apple (11, 5)]

Sorting an array of objects using a comparator

If implementing the Comparable interface is not a suitable option, then you may also use the inline comparator in your code. Please see how the Arrays.sort() method is called in the following code sample. There, we instantiate a new Comparator object which implements the compare() method.

import java.util.Arrays;
import java.util.Comparator;

class Apple {
    private int size;
    private int weight;

    public Apple(int size, int weight) {
        this.size = size;
        this.weight = weight;
    }

    public int getSize() {
        return this.size;
    }

    public int getWeight() {
        return this.weight;
    }

    @Override
    public String toString() {
        return String.format("Apple (%d, %d)", this.size, this.weight);
    }
}

class sample {
    public static void main(String args[]) {
        Apple[] listOfApples = {
            new Apple(5, 8),
            new Apple(10, 7),
            new Apple(11, 5),
            new Apple(8, 10),
            new Apple(7, 9)
        };

        Arrays.sort(listOfApples, new Comparator<Apple>() {
            @Override
            public int compare(Apple apple1, Apple apple2) {
                return apple1.getSize() - apple2.getSize();
            }
        });

        System.out.println(Arrays.toString(listOfApples));
    }
}

If you run the given code, the console output should be like the following.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[Apple (5, 8), Apple (7, 9), Apple (8, 10), Apple (10, 7), Apple (11, 5)]

Using the "bubble sort" algorithm

In the other sections of this tutorial, we've described only the standard API that allows you to sort data in an array. However, you may also create your own code that implements some sorting algorithm.

For example, the following code uses the "bubble sort" algorithm. It's very easy to implement. However the disadvantage is that the code may be very slow on a large amount of data. The complexity of the algorithm is O(n^2)

import java.util.Arrays;

class DataTools {
    public static void bubbleSorting(int[] values) {
        final int arrayLength = values.length;

        for (int i = 0; i < arrayLength; i++) {
            for (int j = 1; j < arrayLength - i; j++){
                if (values[j - 1] > values[j]) {
                    int tempValue = values[j - 1];

                    values[j - 1] = values[j];
                    values[j] = tempValue;
                }
            }
        }
    }
}

class sample {
    public static void main(String args[]) {
        int[] listOfNumbers = {37, 29, 123, 32, 15, 83, 22, 41, 83, 17};

        DataTools.bubbleSorting(listOfNumbers);

        System.out.println(Arrays.toString(listOfNumbers));
    }
}

The given code should produce output like the following.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[15, 17, 22, 29, 32, 37, 41, 83, 83, 123]

Using the "selection sort" algorithm

As an alternative, you may also try to use the "selection sort" algorithm to sort the data in an array. In some conditions, it may work a little faster than the "bubble sort" algorithm. The actual implementation is given below.

import java.util.Arrays;

class DataTools {
    public static void selectionSorting(int[] values) {
        final int arrayLength = values.length;

        for (int i = 0; i < arrayLength - 1; i++) {
            int currentIndex = i;

            for (int j = i + 1; j < values.length; j++) {
                if (values[j] < values[currentIndex]) {
                    currentIndex = j;
                }
            }

            int minValue = values[currentIndex];

            values[currentIndex] = values[i];
            values[i] = minValue;
        }
    }
}

class sample {
    public static void main(String args[]) {
        int[] listOfNumbers = {37, 29, 123, 32, 15, 83, 22, 41, 83, 17};

        DataTools.selectionSorting(listOfNumbers);

        System.out.println(Arrays.toString(listOfNumbers));
    }
}

Also, if you run the given code, the console should contain output like it's shown below.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[15, 17, 22, 29, 32, 37, 41, 83, 83, 123]

Using the "insertion sort" algorithm

The other option is to use the "insertion sort" algorithm. It's very simple as well and can be easily added to any project. However, this method can be efficient only for small data sets, but there may be performance issues with large arrays.

import java.util.Arrays;

class DataTools {
    public static void insertionSorting(int values[]) {
        final int arrayLength = values.length;

        for (int j = 1; j < arrayLength; j++) {
            int currentKey = values[j];
            int i = j - 1;

            while ((i >= 0) && (values[i] > currentKey)) {
                values[i + 1] = values [i];
                i--;
            }

            values[i + 1] = currentKey;
        }
    }
}

class sample {
    public static void main(String args[]) {
        int[] listOfNumbers = {37, 29, 123, 32, 15, 83, 22, 41, 83, 17};

        DataTools.insertionSorting(listOfNumbers);

        System.out.println(Arrays.toString(listOfNumbers));
    }
}

Now, you can try to run the given code sample. It will produce the output like it's shown below.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[15, 17, 22, 29, 32, 37, 41, 83, 83, 123]

It is worth mentioning that there are much more sorting algorithms available. There are other methods that are more efficient when sorting large and complex arrays. You may consider reading the relevant guides that describe the sorting algorithms in detail.

Conclusion

As you see, it's very easy to sort data in Java. This language provides various options that can be used in the code. If you need to quickly sort some simple arrays, then the Arrays.sort() method may help. It should fulfill most of the needs. But in more advanced situations, you may consider using the custom comparator that allows to specify how exactly the objects are compared.

Related Articles

Cup of coffee on saucer

How to read a file to string in Java

Light trails on highway at night

How to split a string in Java

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *