How To Sort An Array In Java

In computer programming, sorting an array is a fundamental activity, and Java offers a range of built-in methods for doing so. Sorting arrays can be a vital task in enhancing the performance and efficiency of your code, whether you are working on a small project or a large-scale application. You can sort an array using a variety of algorithms in Java, including bubble sort, insertion sort, quicksort, and merge-sort.

Depending on the size and complexity of the array you’re working with, each algorithm offers pros and cons. We’ll look at some of the most popular sorting algorithms in Java in this blog post and show you how to use them in your own applications.

Why there is a need to sort the array

  1. Improved performance: By making it easier to access and use the data, sorting an array can significantly increase the performance of your code.
  2. Simpler searching: Sorted arrays make it easier to use binary search techniques, which efficiently search and retrieve sorted data.
  3. Data manipulation: Sorted arrays can facilitate data manipulation by facilitating operations like combining with other arrays or deleting duplicates.
  4. A sorted array can make your code easier to read and comprehend, especially for other developers who may be working with it.
  5. API compliance: Since a lot of Java libraries and APIs depend on sorted data, sorting an array may be important to guarantee compatibility with these tools.

Various Methods on How to Sort an Array in Java

  1. Arrays.sort() method: The Java API includes a built-in method that uses ascending order to sort an array. Both objects that implement the Comparable interface and all primitive data types are compatible with it.
  2. Arrays.paralledSort() method: Similar to Arrays.sort(), this method sorts the array more quickly by using parallel processing. Versions of Java 8 and later support it.
  3. Collections.sort() method: This method sorts a list of items in ascending order, but it can also sort an array if the array is first turned into a list.

A thorough explanation of each strategy

1. Array.sort() method:

An array can be sorted in ascending order using Java’s built-in Arrays.sort() function. The array is sorted using the quicksort algorithm by the method.

You must supply the array as a parameter to the Arrays.sort() method in order to use it. The following sample programme shows how to utilise the Arrays.sort() function:

Example code:

import java.util.Arrays;
 
public class Main {
    public static void main(String[] args) {
             // Initialize an array
        int[] arr = {4, 1, 8, 9, 31, 4, 54, 78};
       
        // Sort the array in ascending order
        Arrays.sort(arr);

       System.out.print(“Sorted Array: ”);

        // Loop through the array and print each element
        for(int i=0; i<arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
 
    }
}

Output:

Sorted Array: 1 4 4 8 9 31 54 78

Explanation of Code:

  1. We first declare an integer array called “arr” and initialise it with some unsorted values.
  2. We then call the Arrays.sort() method and pass the “arr” array as an argument to the method.
  3. The method then sorts the array in ascending order.
  4. Finally we use a for loop to print the values inside the “arr” array to the console.

2. Arrays.parallelSort() method:

An array can be sorted in ascending order using the quicksort algorithm and the parallel processing option with the built-in Java method Arrays.parallelSort(). For big arrays, the approach is faster since it sorts the array in parallel utilising several threads.

The Arrays.parallelSort() method can use several threads to sort various areas of the array in parallel, in contrast to the regular Arrays.sort() method, which sequentially sorts the array in a single thread. When applied to huge arrays that can benefit from parallel processing, this can result in noticeable speed increases.

Example Code:

import java.util.Arrays;


class Main {
    public static void main (String[] args) {
        // Initialize an array
        int[] arr = {4, 1, 8, 9, 31, 4, 54, 78};

       // Sort the array in ascending order
        Arrays.parallelSort(arr);

       System.out.print(“Sorted Array: ”);


       // Loop through the array and print each element
        for(int i=0; i<arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}

Output:

Sorted Array: 1 4 4 8 9 31 54 78

Explanation of Code:

  1. We first declare an integer array called “arr” and initialise it with some unsorted values.
  2. We then call the Arrays.parallelSort() and pass the “arr” array as an argument to the method.
  3. The method then sorts the array in ascending order.
  4. Finally we use a for loop to print the values inside the “arr” to the console.

3. Collections.sort() method:

A java built-in method for sorting collections of objects is Collections.sort(). Lists, sets, and arrays can all be sorted in ascending order using this technique.

Syntax for using Collections.sort() method is as follows:

Collections.sort(List<T> list);

Where T stands for the list’s element type.

You must import the java.util.Collections class in order to use the Collections.sort() method. A list of elements can then be created and send as an argument to the sort() method. The list’s components will be arranged in ascending order.

Code:

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

public class Main {
    public static void main(String[] args) {
        // Initialize an array
        Integer[] arr = {4, 1, 8, 9, 31, 4, 54, 78};

        // Convert the array to ArrayList
        ArrayList<Integer> list = new ArrayList<>(Arrays.asList(arr));

        // Sort the ArrayList using Collections.sort()
        Collections.sort(list);

        // Convert the sorted ArrayList back to array
        Integer[] sortedArr = list.toArray(new Integer[list.size()]);

        // Print the original array and sorted array
        System.out.println("Original Array: " + Arrays.toString(arr));
        System.out.println("Sorted Array: " + Arrays.toString(sortedArr));
    }
}

Output:

Original Array: [4, 1, 8, 9, 31, 4, 54, 78]
Sorted Array: [1, 4, 4, 8, 9, 31, 54, 78]

Explanation of Code:

  1. We import the required classes, such as Arrays, ArrayLists, and Collections, from the java.util package.
  2. We first declare an integer array called “arr” and initialise it with some unsorted values.
  3. We then convert the array to the list using Arrays.asList() functions.
  4. We then sort the list using Collections.sort() function.
  5. Sorted list is then converted to an array using the list.toArray() function.
  6. Using Arrays.toString() function, we print the initial array as well as the sorting array.

Best Approach to Sort an Array in Java:

The best method to sort an array is Arrays.sort() method. The reason being:

  1. Easy to use: A built-in function found in the Java standard library is called arrays.sort(). Because developers do not need to design their own sorting algorithm, it is simple to use and saves time.
  2. Efficient: A highly optimised dual-pivot quicksort algorithm is used by the Arrays.sort() method to quickly sort arrays of any size. Even on big arrays, it functions well.
  3. Consistent and Reliable: Arrays.sort() id dependable and consistent across platforms and Java versions. It makes sure that the array;s elements are always in the same order throughout all of the programs, executions.
  4. Support all data types: All array data types, including simple data types like int and double as well as complex data types like objects, can be sorted using the Arrays.sort() method.
  5. Can be used with Comparable and Comparator: More flexibility and control over the sorting process are provided by the Arrays.sort() function, which may be used with classes that implement the Comparable interface or with a separate Comparator object.

Sample problem to Sort an Array in Java

Problem 1: How to sort an integer array in Java? Write a program that takes an array of integers as input and sorts it in ascending order using the Arrays.sort().

Solution:

  1. The program starts by importing the java.util.Arrays and java.util.Scanner classes.
  2. In the main() method, a new Scanner object is created to read user input.
  3. The user is prompted to enter the size of the array and its elements. The input is stored in the size variable and the arr array.
  4. The Arrays.sort() method is used to sort the arr array in ascending order.
  5. The sorted array is printed using the Arrays.toString() method.
  6. Finally, the Scanner object is closed to free up system resources.

Code:

import java.util.Arrays;
import java.util.Scanner;

public class SortArray {

    public static void main(String[] args) {

        // create scanner object for user input
        Scanner scanner = new Scanner(System.in);

        // prompt user to enter array size and elements
        System.out.print("Enter the size of the array: ");
        int size = scanner.nextInt();
        int[] arr = new int[size];
        System.out.print("Enter the array elements: ");
        for (int i = 0; i < size; i++) {
            arr[i] = scanner.nextInt();
        }

        // sort the array in ascending order using Arrays.sort()
        Arrays.sort(arr);

        // print the sorted array
        System.out.println("The sorted array is: " + Arrays.toString(arr));

        // close scanner object
        scanner.close();
    }
}

Output:

Enter the size of the array: 5
Enter the array elements: 4 1 3 5 2
The sorted array is: [1, 2, 3, 4, 5]

Problem 2: Write a program that takes an array of integers as input and finds the kth smallest number in the array using the Arrays.parallelSort() method.

Solution:

  1. The program takes an array of integers as input and stores it in the arr variable.
  2. The program also takes an integer k which represents the kth smallest element to find in the array.
  3. The Arrays.parallelSort() method is called on the arr array, which sorts it in ascending order.
  4. The kth smallest element is accessed using the index k-1 since arrays are 0-indexed in Java.
  5. The program prints out the kth smallest element.

Code:

import java.util.Arrays;

public class KthSmallestElement {

    public static void main(String[] args) {
       // Initialize the array 
        int[] arr = {10, 7, 8, 9, 1, 5};
        int k = 3; // kth smallest element

        // sort the array
        Arrays.parallelSort(arr);

        // print the kth smallest element to the console
        System.out.println(k + "th smallest element is " + arr[k-1]);
    }
}

Output:

3th smallest element is 8

Problem 3: Write a program that takes an array of String as input and sorts it in ascending order using the Collections.sort() method.

Solution:

  1. ArrayList, Collections, and Scanner are some important classes that are imported from the java.util package.
  2. We prompt the user to enter the size of the array and store it in the variable.
  3. String ArrayList is created to store the String values.
  4. We then prompt the user to enter the size number of String values and add them to the stringArray using the add() method.
  5. The stringArray is sorted in ascending order using Collections.sort().
  6. The sorted array is displayed using a for loop.

Code:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the size of the array: ");
        int size = scanner.nextInt();

        // Create an ArrayList to store the floating-point numbers
        ArrayList<String> stringArray = new ArrayList<String>();

        System.out.println("Enter " + size + " String values:");
        for (int i = 0; i < size; i++) {
            String str = scanner.next();
            stringArray.add(str);
        }

        // Sort the ArrayList using Collections.sort() method
        Collections.sort(stringArray);

        // Print the sorted array
        System.out.println("Sorted array in ascending order:");
        for (String str : stringArray) {
            System.out.print(str + " ");
        }

        scanner.close();
    }
}

Output:

Enter the size of the array: 5
Enter 5 String values:
Banana
Orange
Pear
Grape
Apple
Sorted array in ascending order:
Apple Banana Grape Orange Pear

Conclusion

In conclusion, sorting an array is a fundamental programming activity, and Java provides a number of efficient ways on how to order an array in Java. Three frequently used Java methods for sorting arrays have been covered in this blog: Arrays.sort(), Collections.sort(), and Arrays.parallelSort ().

We also learned how to sort string array in java.

It’s critical to select the best sorting approach based on the array’s size and kind of data. Developers can select the best sorting strategy for their particular use case by having a working knowledge of these three techniques. In conclusion, sorting an array in Java is a crucial ability for any programmer, and understanding these sorting techniques can significantly increase the program’s efficacy and efficiency.