Interview Kickstart has enabled over 21000 engineers to uplevel.
Knowing how to sort an array in Java in several ways is a handy skill for software engineers. In this article, you’ll learn different methods of sorting numerical arrays in ascending/descending order and string arrays in lexicographical/reverse lexicographical order. We’ll also discuss how to sort subarrays and more!
If you are preparing for a tech interview, check out our technical interview checklist, interview questions page, and salary negotiation e-book to get interview-ready! Also, read Java Scanner reset(), HashMap in Java, and PriorityQueue in Java for more insights and guidance on Java concepts.
Having trained over 11,000 software engineers, we know what it takes to crack the toughest tech interviews. Our alums consistently land offers from FAANG+ companies. The highest ever offer received by an IK alum is a whopping $1.267 Million!
At IK, you get the unique opportunity to learn from expert instructors who are hiring managers and tech leads at Google, Facebook, Apple, and other top Silicon Valley tech companies.
Want to nail your next tech interview? Sign up for our FREE Webinar.
In this article, we’ll learn:
An array is a data structure that stores a collection of homogenous data. In other words, the elements stored in an array all belong to the same data type. In Java, arrays have an additional feature. Arrays are always dynamically allocated in Java, so the exact amount of memory needed can be allocated to them. This also leads to increased storage efficiency.
For more details, check out our page on Arrays in Java.
Sorting refers to arranging several items into an ordered sequence. Often, it involves numerical and lexicographical sorting in ascending or descending order. There are many sorting algorithms to aid us in this process, and each major sorting algorithm has certain types of cases it is especially useful.
To learn more about sorting, check out our page on Sorting Algorithms, Time and Space Complexities of Sorting Algorithms, and Stability in Sorting Algorithms.
Numerical or lexicographical sorting of an array in ascending or descending order can be done with the help of in-built methods like sort() and reverseOrder(). If you want to know how to sort an array in Java using other ways, you can also write your own methods, and use loops like for loop, etc. These are the core concepts you need to know as you learn how to sort an array in Java. Let us look at how these methods can be chosen and used based on the kind of sorting needed.
We can learn how to sort an array in Java in ascending order in several ways. We can learn:
Let us take a look at how an array can be sorted in ascending order using these three methods with the help of examples:
Code:
import java.util.Arrays;
class ascendingUsingSort
{
public static void main(String[] args)
{
// Creating an array of data type double
double [] sampleArray = new double [] {4.5, 5.3, 4.9, 9.8, 2.9, 1.7, 6.5, 7.0};
// Using the sort() method in the class Arrays on sampleArray
Arrays.sort(sampleArray);
System.out.println("Here's the sample array sorted in ascending order: ");
// Printing the sorted sampleArray using for loop
for (int i = 0; i < sampleArray.length; i++)
{
System.out.println(sampleArray[i]);
}
}
}
Output:
Here's the sample array sorted in ascending order:
1.7
2.9
4.5
4.9
5.3
6.5
7.0
9.8
Note: The logic within the user-defined function can be written directly inside main() if you don’t want to use a user-defined method. The logic inside the user-defined method can be implemented differently. (The same applies to the user-defined example when sorting in descending order, covered later in the article.)
Code:
import java.util.Arrays;
class ascendingUsingUserDefinedMethod
{
public static void main(String[] args)
{
// Creating an array of data type double
double [] sampleArray = new double [] {4.5, 5.3, 4.9, 9.8, 2.9, 1.7, 6.5, 7.0};
System.out.println("Here's the sample array sorted in ascending order using user-defined function: ");
// Using user-defined function to sort sampleArray in ascending order
userdefAscendingSort(sampleArray, sampleArray.length);
for(int i=0; i<sampleArray.length;i++)
// Printing the sorted sampleArray
System.out.println(sampleArray[i]);
}
private static void userdefAscendingSort(double inputArray[], int arraySize)
{
for (int i = 1; i < arraySize; i++)
{
int j = i;
double temporaryHolder = inputArray[i];
while ((j > 0) && (inputArray[j-1] > temporaryHolder))
{
inputArray[j] = inputArray[j-1];
j--;
}
inputArray[j] = temporaryHolder;
}
}
}
Output:
Here's the sample array sorted in ascending order using user-defined function:
1.7
2.9
4.5
4.9
5.3
6.5
7.0
9.8
We can learn how to sort an array in Java in descending order in several ways. We can learn::
Let us take a look at how an array can be sorted in descending order using these three methods with the help of examples:
Java’s Collections class offers a static method called the reverseOrder() method that sorts an array in descending or reverse order. As a static method, it can be directly invoked using the name of its class. In Java, reverseOrder() doesn’t parse any parameter to sort and returns a comparator that reverses the order, which is by default ascending for the sort() method.
We’ll now sort an int array in descending order in Java. Please note that since the reverseOrder method does not work for primitive data types, we’ve taken the sampleArray of type Integer in this example. Also, note that initially, the elements are sorted in ascending order using sort(). Then the reverseOrder() method returns a comparator that reverses the default ascending order, giving us the array sorted in descending order.
Code:
import java.util.Arrays;
import java.util.Collections;
class descendingUsingreverseOrder
{
public static void main(String[] args)
{
// Creating an array of data type integer
Integer [] sampleArray = {4, 5, 4, 9, 2, 1, 6, 7};
// Using the reverseOrder() method to sort sampleArray in descending order
Arrays.sort(sampleArray, Collections.reverseOrder());
System.out.println("Here's the sample array sorted in descending order: ");
for(int i=0; i<sampleArray.length;i++)
// Printing the sorted sampleArray
System.out.println(sampleArray[i]);
}
}
Output:
Here's the sample array sorted in descending order:
9
7
6
5
4
4
2
1
Code:
import java.util.Arrays;
class descendingUsingUserDefinedMethod
{
public static void main(String[] args)
{
// Creating an array of data type double
double [] sampleArray = new double [] {4.5, 5.3, 4.9, 9.8, 2.9, 1.7, 6.5, 7.0};
System.out.println("Here's the sample array sorted in descending order using user-defined function: ");
// Using user-defined function to sort sampleArray in descending order
userdefDescendingSort(sampleArray, sampleArray.length);
for(int i=0; i<sampleArray.length;i++)
// Printing the sorted sampleArray using user-defined method
System.out.println(sampleArray[i]);
}
private static void userdefDescendingSort(double inputArray[], int arraySize)
{
for (int i = 1; i < arraySize; i++)
{
int j = i;
double temporaryHolder = inputArray[i];
while ((j > 0) && (inputArray[j-1] < temporaryHolder))
{
inputArray[j] = inputArray[j-1];
j--;
}
inputArray[j] = temporaryHolder;
}
}
}
Output:
Here's the sample array sorted in descending order using user-defined function:
9.8
7.0
6.5
5.3
4.9
4.5
2.9
1.7
We can also sort strings in lexicographical or reverse lexicographical order using sort and reverseOrder.
Code:
import java.util.Arrays;
class ascendingUsingreverseOrder
{
public static void main(String[] args)
{
// Creating an array of data type String
String [] sampleArray = {"a", "b", "c", "d", "e"};
// Using the reverseOrder() method to sort sampleArray in ascending order
Arrays.sort(sampleArray);
System.out.println("Here's the sample array sorted in ascending order: ");
for(int i=0; i<sampleArray.length;i++)
// Printing the sorted sampleArray
System.out.println(sampleArray[i]);
}
}
Output:
Here's the sample array sorted in ascending order:
a
b
c
d
e
Code:
import java.util.Arrays;
import java.util.Collections;
class descendingUsingreverseOrder
{
public static void main(String[] args)
{
// Creating an array of data type string
String [] sampleArray = {"a", "b", "c", "d", "e"};
// Using the reverseOrder() method to sort sampleArray in descending order
Arrays.sort(sampleArray, Collections.reverseOrder());
System.out.println("Here's the sample array sorted in descending order: ");
for(int i=0; i<sampleArray.length;i++)
// Printing the sorted sampleArray
System.out.println(sampleArray[i]);
}
}
Output:
Here's the sample array sorted in descending order:
e
d
c
b
a
We can also sort a subarray using sort as the syntax for sort() can also be:
Syntax:
sort(sampleArray, sortFrom, sortTill)
To better understand how to use the sort() method to sort a subarray, check out this example:
Code:
import java.util.Arrays;
class ascendingUsingreverseOrder
{
public static void main(String[] args)
{
// Creating an array of data type integer, note that number 2 is at index 4
Integer [] sampleArray = {4, 5, 4, 9, 2, 1, 6, 7};
// Using the reverseOrder() method to sort sampleArray in ascending order
Arrays.sort(sampleArray, 4, sampleArray.length);
System.out.println("Here's the sample array sorted from position 4 to the end of the array, in ascending order: ");
for(int i=0; i<sampleArray.length;i++)
// Printing the sorted sampleArray
System.out.println(sampleArray[i]);
}
}
Output:
Here's the sample array sorted from position 4 to the end of the array, in ascending order:
4
5
4
9
1
2
6
7
Q1. What type of data could we use in Arrays.sort() to sort an array in Java?
The sort() method can be used for sorting an array of any primitive data type like int, float, byte, char, short, boolean, etc.
Q2. Which method is used to sort an array in Java?
The sort() method is used to sort an array in Java. By default, it sorts an array in ascending order, but by using reverseOrder() inside it as a parameter, we can also get the array sorted in descending order.
Q3. What algorithm does the sort() method in Java use to sort an array?
The sort() method in Java uses a combination of quicksort, insertion sort, and mergesort for sorting.
Q4. How to sort an array in Java in ascending order?
We can sort an array in Java in ascending order using the sort() method, for loop, user-defined method, etc.
Q5. How to sort an array in Java in descending order?
We can sort an array in Java in descending order using the reverseOrder() method, for loop, user-defined method, etc.
Whether you’re a Coding Engineer gunning for Software Developer or Software Engineer roles, a Tech Lead, or you’re targeting management positions at top companies, IK offers courses specifically designed for your needs to help you with your technical interview preparation!
If you’re looking for guidance and help with getting started, sign up for our FREE webinar. As pioneers in the field of technical interview preparation, we have trained thousands of software engineers to crack the most challenging coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!
Attend our webinar on
"How to nail your next tech interview" and learn