Register for our webinar

How to Nail your next Technical Interview

1 hour
Loading...
1
Enter details
2
Select webinar slot
*Invalid Name
*Invalid Name
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
*All webinar slots are in the Asia/Kolkata timezone
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.
close-icon
Iks white logo

You may be missing out on a 66.5% salary hike*

Nick Camilleri

Head of Career Skills Development & Coaching
*Based on past data of successful IK students
Iks white logo
Help us know you better!

How many years of coding experience do you have?

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Iks white logo

FREE course on 'Sorting Algorithms' by Omkar Deshpande (Stanford PhD, Head of Curriculum, IK)

Thank you! Please check your inbox for the course details.
Oops! Something went wrong while submitting the form.
Our June 2021 cohorts are filling up quickly. Join our free webinar to Uplevel your career
close
closeAbout usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar

How to Sort an Array in Java

Last updated by Ashwin Ramachandran on Apr 01, 2024 at 01:04 PM | Reading time: 13 minutes

The fast well prepared banner

Attend our Free Webinar on How to Nail Your Next Technical Interview

WEBINAR +LIVE Q&A

How To Nail Your Next Tech Interview

How to Sort an Array in Java
Hosted By
Ryan Valles
Founder, Interview Kickstart
strategy
Our tried & tested strategy for cracking interviews
prepare list
How FAANG hiring process works
hiring process
The 4 areas you must prepare for
hiring managers
How you can accelerate your learnings

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:

  • What Is an Array?
  • What Is Sorting?
  • How to Sort an Array in Java?
  • Sorting Array in Ascending Order With Examples
  • Sorting Array in Descending Order With Examples
  • Sorting an Array of Strings
  • How to Sort Subarray in Java?
  • Interview Questions Based on Sorting Arrays in Java
  • Sorting Arrays in Java FAQs

What Is an Array?

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.

What is Sorting?

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.

How to Sort an Array in Java

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.

Sorting Array in Ascending Order With Examples

We can learn how to sort an array in Java in ascending order in several ways. We can learn:

  • How to sort an array in Java in ascending order using the sort() Method
  • How to sort an array in Java in ascending order using the for loop
  • How to sort an array in Java in ascending order using a User-Defined Method

Let us take a look at how an array can be sorted in ascending order using these three methods with the help of examples:

Ascending Order Example: How to Sort an Array in Java Using the sort() Method

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

Ascending Order Example: How to Sort an Array in Java Using for Loop Implemented as a User-Defined Method

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

How to Sort an Array in Java in Descending Order With Examples

We can learn how to sort an array in Java in descending order in several ways. We can learn::

  • How to sort an array in Java in descending order using the reverseOrder() Method
  • How to sort an array in Java in descending order using the for loop
  • How to sort an array in Java in descending order using a User-Defined Method

Let us take a look at how an array can be sorted in descending order using these three methods with the help of examples:

Descending Order Example: Sort Array in Java Using the reverseOrder() Method

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

Descending Order Example: Sort Array in Java Using for Loop Implemented as a User-Defined Method

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

Sorting an Array of Strings

We can also sort strings in lexicographical or reverse lexicographical order using sort and reverseOrder.

String Example: Sort Array In Ascending or Lexicographical Order

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

String Example: Sort Array in Descending or Reverse Lexicographical Order

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

How to Sort Subarray in Java

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

Interview Questions on How to Sort Arrays in Java

  1. Explain the usage of Arrays.sort() in Java with the help of examples
  2. What is the syntax of sort()? What are the parameters, and which ones are optional? Is the function overloaded?
  3. What is ArrayStoreException in java? When will you get this exception?
  4. Can you pass the negative number as an array size?
  5. How do you sort the array elements?

Solve Problems on Sorting Arrays in Java

  1. Sort a 2-D String Array in reverse- lexicographical order in Java
  2. Sort a 2-D Integer Array in descending order in Java
  3. Sort the subarray of the string array {“a”,“b”,“c”,“d”,“e”,“f”} starting from c and ending at f.
  4. Sort the subarray of the integer array {4,7,3,8,3,9,2,6,1,0} starting from 7 and ending at 1, keeping the first and last element 4 and 0 intact.
  5. Sort only even numbers present in the array {4,7,3,8,3,9,2,6,1,0} while ensuring even numbers are only present in positions that originally had even numbers.

FAQs on How to Sort Arrays in Java

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.

Ready to Nail Your Next Coding Interview?

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!

Sign up now!


Last updated on: 
April 1, 2024
Author

Ashwin Ramachandran

Head of Engineering @ Interview Kickstart. Enjoys cutting through the noise and finding patterns.

Attend our Free Webinar on How to Nail Your Next Technical Interview

Register for our webinar

How to Nail your next Technical Interview

1
Enter details
2
Select webinar slot
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.

How to Sort an Array in Java

Worried About Failing Tech Interviews?

Attend our webinar on
"How to nail your next tech interview" and learn

Ryan-image
Hosted By
Ryan Valles
Founder, Interview Kickstart
blue tick
Our tried & tested strategy for cracking interviews
blue tick
How FAANG hiring process works
blue tick
The 4 areas you must prepare for
blue tick
How you can accelerate your learnings
Register for Webinar
entroll-image