## Pages

Disclosure: This article may contain affiliate links. When you purchase, we may earn a commission.

# 7 Examples to Sort One and Two Dimensional String and Integer Array in Java | Ascending, Descending and Reverse Order

Sorting array is a day-to-day programming task for any software developer.  If you have come from a Computer Science background then you have definitely learned fundamental sorting algorithms like the bubble sort, insertion sort, and quicksort but you don't really need to code those algorithms to sort an array in Java because Java has good support for sorting different types of array. You can use Arrays.sort() method to sort both primitive and object array in Java. But, before using this method, let's learn how the Arrays.sort() method works in Java. This will not only help you to get familiar with the API but also its inner workings.  This method sorts the given array into ascending order, which is the numeric order for primitives and defined by compareTo() or compare() method for objects.

For primitive arrays, like int,  short, character, float, double or long array, this method uses a dual-pivot Quicksort sorting algorithm implemented by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch (author of Effective Java).

This algorithm offers O(n log(n)) performance on many data sets that cause other quicksort algorithms to degrade into their worst quadratic performance like O(n^2) and is typically faster than traditional (one-pivot) Quicksort implementations.

That's why I always said that prefer the library method on my own, you can get it right but with the amount of testing and user exposure the library method gets, you will never get for your implementations.

On the other hand, the object array is sorted using a stable MergeSort algorithm, which ensures that equal elements keep their original position in the sorted array. Implementation of mergesort used in sort(Object[]) is stable, adaptive, and iterative that requires much lesser than O(n log(n)) comparisons when the input array is partially sorted while offering the performance of a traditional mergesort when the input array is randomly ordered.

In the best case, when the input array is almost sorted, this implementation requires approximately O(n) comparisons.

By the way, temporary storage requirements vary from a small constant for nearly sorted input arrays to n/2 object references for randomly ordered input arrays. If you are interested in those nitty-gritty algorithms details, you can also join the Data Structures and Algorithms: Deep Dive Using Java course on Udemy. One of the best courses to learn the fundamentals of data structure and algorithms for Java programmers.

## 7 ways to Sort One and Two Dimensional Array in Java

In order to sort different types of arrays in Java, you can use any of the overloaded versions of the sort() method from the Arrays class. It also has two special methods for sorting object arrays, one sorts the array in the natural order, while others sort them in a custom order of provided comparator.

Since a two-dimensional array is also an array of an array in Java, you can use this method to sort multidimensional arrays in Java also. You will see step-by-step examples of sorting all kinds of arrays in Java in the subsequent section.

### 1. Sorting One Dimensional Array in Ascending Order

Sorting any primitive or object array in ascending order is very easy, all you need to know is the sort() method from java.util.Arrays class. It provides an overloaded method to sort byte, short, char, int, long, float, double, and object arrays.

This method sorts the given array in increasing order using two pivot quicksort algorithms. You can use this method to sort an array of objects which implements either the Comparable or Comparator method. It has an overloaded version, which accepts a Comparator for custom sorting.

Here is an example to sort an int primitive array in ascending order in Java.

```int[] random = { 33, 22, 11, 21, 55, 32, 3, 4 };
System.out.println("Array before sorting : " + Arrays.toString(random));
Arrays.sort(random);
System.out.println("Array after sorting in ascending order : "
+ Arrays.toString(random));

Output:
Array before sorting : [33, 22, 11, 21, 55, 32, 3, 4]
Array after sorting in ascending order : [3, 4, 11, 21, 22, 32, 33, 55]```

You can see that array is now sorted in ascending order which was not the case previously. Btw, if you want to learn more about Java API and how Comparable and Comparator works, I suggest you choose a comprehensive Java course like these best Java Programming courses which is also the most up-to-date Java course, recently updated to cover Java 11 features.

### 2. How to Sort Integer Array in Java

Let's see one more example of the sort() method, this time we will sort an array of Integer objects instead of int primitives. The first line may look similar, but remember autoboxing will convert each int value to Integer, but it can not convert an int[] to Integer[].

That's why the sort method used here is sort(Object[]) and not sort(int[]), this is also obvious when we sort the Integer array into reverse order and passed a reverse order comparator from the Collections class.

```Integer[] elevens = { 44, 22, 55, 11, 33, 66, 77 };
Arrays.sort(elevens);
System.out.println("increasing order : " + Arrays.toString(elevens));
Arrays.sort(elevens, Collections.reverseOrder());
System.out.println("reverse order : " + Arrays.toString(elevens));

Output:
increasing order : [11, 22, 33, 44, 55, 66, 77]
reverse order : [77, 66, 55, 44, 33, 22, 11]```

You can see that now the array is sorted in reverse order as 77, the largest number is present at index 0 or at the first position, and 11, the smallest number is at the last index.

### 3. Sorting String Array in Java - Ascending and Descending Order

A string is not numeric data, it defines its own order which is called lexicographic order, also known as alphabetic order. When you sort an array of String using the sort() method, it sorts an array into natural order defined by Comparable interface, as shown below :

#### 3.1 Sorting String Array in Increasing Order

Here is a code example to sort a String array in ascending order in Java. The order is defined by Comparable which the String class implements. Its called lexicographic order, which is similar to alphabetic and alphanumeric order.

```String[] names = {"John", "Steve", "Shane", "Adam", "Ben"};
System.out.println("String array before sorting : " + Arrays.toString(names));
Arrays.sort(names);
System.out.println("String array after sorting in ascending order : "
+ Arrays.toString(names));

Output:
String array before sorting : [John, Steve, Shane, Adam, Ben]
String array after sorting in ascending order : [Adam, Ben, John, Shane, Steve]```

### 3.2 Sorting String Array in Decreasing Order

Now, let's the example to sort a string array in the descending order. This is just online line change. I have added Collections.soreverOrder() to ever the sorting order for arrays.

```Arrays.sort(names, 0, names.length, Collections.reverseOrder());
System.out.println("String array after sorting in descending order : "
+ Arrays.toString(names));

Output:
String array after sorting in descending order : [Steve, Shane, John, Ben, Adam]```

You can see that String is now sorted in lexicographic order which is a combination of alphabetic and alphanumeric order. If you want to learn more about String in Java, please see The Complete Java MasterClass course on Udemy.

### 4. Sorting Object Array in Java

In order to sort an object array, all elements must implement either a Comparable or Comparator interface to define an order. You can use either use sort(Object[]) method to sort an object array in its natural order, you must ensure that all elements in the array must implement Comparable.

Furthermore, they must be mutually comparable as well, for example, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the array.

Alternatively, you can sort an Object array on custom order using the sort(T[], Comparator) method. as shown in the following example.

```// How to Sort Object Array in Java using Comparator and Comparable
Course[] courses = new Course;
courses = new Course(101, "Java", 200);
courses = new Course(201, "Ruby", 300);
courses = new Course(301, "Python", 400);
courses = new Course(401, "Scala", 500);

System.out.println("Object array before sorting : "
+ Arrays.toString(courses));

Arrays.sort(courses);
System.out.println("Object array after sorting in natural order : "
+ Arrays.toString(courses));

Arrays.sort(courses, new Course.PriceComparator());
System.out.println("Object array after sorting by price : "
+ Arrays.toString(courses));

Arrays.sort(courses, new Course.NameComparator());
System.out.println("Object array after sorting by name : "
+ Arrays.toString(courses));

Output :
Object array before sorting : [#101 Java@200 , #201 Ruby@300 ,
#301 Python@400 , #401 Scala@500 ]
Object array after sorting in natural order : [#101 Java@200 , #201 Ruby@300 ,
#301 Python@400 , #401 Scala@500 ]
Object array after sorting by price : [#101 Java@200 , #201 Ruby@300 ,
#301 Python@400 , #401 Scala@500 ]
Object array after sorting by name : [#101 Java@200 , #301 Python@400 ,
#201 Ruby@300 , #401 Scala@500 ]```

### 5. How to sort Array in Reverse order in Java

Sorting an object array in descending order is easy because Java API provides a sort() method which takes both array and Comparator, which can be used to sort array in reverse order.

For example, you can sort a String array in reverse order by using the Collections.reverseComparator() method, which is a built-in reverse comparator from the Collections utility class.

You can sort all numeric arrays e.g. Integer, Double or Float using the same technique. But, when it comes to sorting a primitive array in reverse order, you are left with nothing. You can not sort a primitive array with a reverse comparator and Java doesn't provide a direct method for sorting in descending order.

You can do two things, write your own method using any efficient sorting algorithm like quicksort, sort the array in descending order, or just sort the array using the Arrays.sort() method and reverse it.

Former can be a clean approach but you would likely be going to get efficiency which comes with a library method like Arrays.sort(), which is a double pivot quicksort implementation and offers O(n log(n)) performance on many data sets that cause other quicksorts to degrade to quadratic performance.

The second approach is better but will cost you an additional O(n) performance. There is one more way, going via the Collection route, you can convert the array to list and sort the list in reverse order, but you will not get any performance benefit.

### 6. How to Sort Two dimensional Array in Java? Examples

There is no easy way to sort a multi-dimensional array in Java, Java API provides no direct method to sort a two or three-dimensional array, maybe because it's not clear how do you want to sort a multi-dimensional array.

If you want to sort your two-dimensional array on columns then you can use our ColumnComparator class which implements a Comparator interface to sort column data. You can see the full code of this class in our program section. It also uses Java enum to define sorting orders like ASCENDING and DESCENDING, which is much better than a blank boolean variable.

In the following examples, we first sort a two-dimensional array in ascending order on the first column, while in the second example we sort it on increasing order but this time only the second column.

If you want to sort all columns of a multidimensional array, you can just extend this program to iterate over an array, and passing column index to ColumnCompartor.

#### 6.1 Sorting Array in Ascending Order on the first Column

This is the code example to sort a two-dimension array in the ascending order of the first column. This is also the standard way to sort a 2D array in Java and it's also more common than sorting array on the second column which we will see in the next example.
```Integer[][] numbers = { {9, 6, 5}, {3, 2, 4}, {1, 5, 7} };
System.out.println("Two dimensional array before sorting : "
+ Arrays.deepToString(numbers));
Arrays.sort(numbers, new ColumnComparator(0, SortingOrder.ASCENDING));
System.out.println("2D array after sorting in ascending order on first column : "
+ Arrays.deepToString(numbers));

Output
Two dimensional array before sorting : [[9, 6, 5], [3, 2, 4], [1, 5, 7]]
2D array after sorting in ascending order on first column :
[[1, 5, 7], [3, 2, 4], [9, 6, 5]]
```

#### 6.2 Sorting Array in Ascending Order on Second Column

Here is a code example to sort a two-dimensional array in ascending order of the second column in Java. This is a rare case but if you are implementing real-world applications you will face this kind of scenario where you need to sort a 2D array on secondary data.
```Arrays.sort(numbers, new ColumnComparator(1,SortingOrder.DESCENDING));
System.out.println("Sorting two dimensional String array in Java,
Second column, Ascending order : " + Arrays.deepToString(numbers));

Output
Sorting two dimensional String array in Java, Second column,
Ascending order : [[9, 6, 5], [1, 5, 7], [3, 2, 4]]```

### 7. Java Program to Sort Array in Java

Here is our complete Java program, which you can just copy-paste and run in Eclipse by right click. Alternatively, you can copy the source in a text file with the name same as the main class, compile it using the javac command and run it by using the java command directly from the command prompt.

This contains code to sort a primitive array on increasing order, sorting integer and string array in ascending and descending order, sorting object arrays, and sorting 2D array columns.

If you have any questions or face any problems while running this sample program, please let us know.

```import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;

/**
* Couple of examples of Multi-dimensional array in Java. It shows how to
* declare multidimensional array in Java, how to initialise them both inline
* and using for loop and how to access particular elements from two dimensional
* array.
*
* @author Javin Paul
*/

public class ArraySorter {

public static void main(String args[]) {

// How to sort Integer array in Java - ascending order
int[] random = { 33, 22, 11, 21, 55, 32, 3, 4 };
System.out.println("Array before sorting : " + Arrays.toString(random));
Arrays.sort(random); // sorts primitive array using quicksort algorithm
System.out.println("Array after sorting in ascending order : "
+ Arrays.toString(random));

// How to sort String array in Java
String[] names = {"John", "Steve", "Shane", "Adam", "Ben"};
System.out.println("String array before sorting : " + Arrays.toString(names));

Arrays.sort(names); // sorts object array using mergesort algorithm
System.out.println("String array after sorting in ascending order : "
+ Arrays.toString(names));

// How to sort String array in descending order in Java
Arrays.sort(names, 0, names.length, Collections.reverseOrder());
System.out.println("String array after sorting in descending order : "
+ Arrays.toString(names));

// How to Sort Object Array in Java using Comparator and Comparable
Course[] courses = new Course;
courses = new Course(101, "Java", 200);
courses = new Course(201, "Ruby", 300);
courses = new Course(301, "Python", 400);
courses = new Course(401, "Scala", 500);

System.out.println("Object array before sorting : "
+ Arrays.toString(courses));
Arrays.sort(courses);
System.out.println("Object array after sorting in natural order : "
+ Arrays.toString(courses));

Arrays.sort(courses, new Course.PriceComparator());
System.out.println("Object array after sorting by price : "
+ Arrays.toString(courses));

Arrays.sort(courses, new Course.NameComparator());
System.out.println("Object array after sorting by name : "
+ Arrays.toString(courses));

// How to sort two dimensional array in Java on first column, increasing order
Integer[][] numbers = { {9, 6, 5}, {3, 2, 4}, {1, 5, 7} };
System.out.println("Two dimensional array before sorting : "
+ Arrays.deepToString(numbers));
Arrays.sort(numbers, new ColumnComparator(0, SortingOrder.ASCENDING));
System.out.println("2D array after sorting
in ascending order on first column : "
+ Arrays.deepToString(numbers));

// sorting 2D array on second column in descending order
Arrays.sort(numbers, new ColumnComparator(1,SortingOrder.DESCENDING));
System.out.println("Sorting two dimensional String array in Java,
Second column, Ascending order : "
+ Arrays.deepToString(numbers));

}

}

/*
* Simple Enum to represent sorting order e.g. ascending and descending order
*/
enum SortingOrder{
ASCENDING, DESCENDING;
};

/*
* Utility Comparator class to sort two dimensional array in Java
*/
class ColumnComparator implements Comparator<Comparable[]> {
private final int iColumn;
private final SortingOrder order;

public ColumnComparator(int column, SortingOrder order) {
this.iColumn = column;
this.order = order;
}

@Override
public int compare(Comparable[] c1, Comparable[] c2) {
int result = c1[iColumn].compareTo(c2[iColumn]);
return order==SortingOrder.ASCENDING ? result : -result;
}
}

class Course implements Comparable<Course>{
int id;
String name;
int price;

public Course(int id, String name, int price){
this.id = id;
this.name = name;
this.price = price;
}

@Override
public int compareTo(Course c) {
return this.id - c.id;
}

@Override
public String toString() {
return String.format("#%d %s@%d ", id, name, price);
}

public static class PriceComparator implements Comparator<Course>{
@Override
public int compare(Course c1, Course c2) {
return c1.price - c2.price;
}
}

public static class NameComparator implements Comparator<Course>{
@Override
public int compare(Course c1, Course c2) {
return c1.name.compareTo(c2.name);
}
}

}
```
That's all about how to sort an array in Java. We have learned to sort both primitive and object arrays in both ascending and descending order. The only piece which is a bit tricky is sorting primitive arrays in reverse order because there is no direct method to do that in Java.

You need to go through steps like first sorting them in increasing order and then reversing or writing your method to do the job or converting an array to a list and vice-versa. In any case, use a library method to do sorting for performance and robustness, as you know-how using a two pivot quicksort method on the Arrays sort() method gives better performance for arrays for which other similar sorting algorithms result in O(n^2).

Autoboxing cannot help to convert an int[] to Integer[] so there is no shortcut also. Prefer List over array due to this reason but for performance-critical code use a primitive array to save memory and reduce GC cost.

Here are some useful Array and Data Structure resources to learn more about array data structure :
• 22 Array Concepts Interview Questions in Java (questions)
• How to create an array from ArrayList of String in Java (tutorial)
• How to remove duplicates from an unsorted array in Java? (solution)
• 20+ String Coding Problems from Interviews (questions)
• How to reverse an array in place in Java? (solution)
• 10 Data Structure Courses to Crack Programming Interviews (courses)
• How to find all pairs whose sum is equal to a given number in array? (solution)
• Iterative Binary Search Algorithms in Java (algorithm)
• 10 Algorithms Books Every Programmer Should Read (books)
• 10 Free Data Structure and Algorithm Courses for Beginners (courses)
• Top 20 Searching and Sorting Interview Questions (questions)
• How to make a binary search tree in Java? (solution)
• 50+ Data Structure and Algorithms Interview Questions (questions)
Thanks for reading this article so far. If you like this Array to String the tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are looking to learn Data Structure and Algorithms from scratch or want to fill gaps in your understanding and looking for some free courses, then you can check out this list of Free Algorithms Courses to start with.

1. how you write code in colorfull texyt please tell

2. What is the complexity of sorting using Arrays utility?

1. It's two pivot quicksort algorithm for primitives and a stable mergesort for refernece types. which means on average you get performance of O(nlogn) while sorting array using Arrays.sort() method.

3. vishal shingote ..use the Eclipse tool i hope it will help you.

4. I found your example on sorting by the second column confusing.
I think this is because you have labelled that section Ascending, text output, Ascending, and then called the Enum Descending?

5. You can also sort the array parallel in Java 8 by using Arrays.parallelSort() method. This is going to be much faster than existing sequential Arrays.sort() method, especially in modern days multi-core CPU. It internally use fork/join pool for multi threading.

6. 7. package javaapplication8;

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

public class SortingArrays {

public static void main(String[] args) {

Scanner input = new Scanner (System.in);

int [][] number = new int ;

for (int i = 0; i <3; i++) {

for (int j = 0; j < 4; j++) {

System.out.printf(" [%d][%d] = ",i,j);

number[i][j]= input.nextInt();

}

}

Arrays.sort(ints);

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 4; j++) {

System.out.print(" "+ number[i][j]);

}

}

System.out.println(" " );
}

}

1. import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

/**SORTING 2D ARRAY, by John Kerry Omoti, Lagos, Nigeria. **/

public class SortingArrays {

public static void main(String[] args) {

//INPUT ELEMENTS OF THE 2D ARRAY
System.out.println("\nENTER INPUT ELEMENTS FOR int [][] number\n")
;
Scanner input = new Scanner (System.in);

int [][] number = new int ;

for (int i = 0; i <3; i++) {

for (int j = 0; j < 4; j++) {

System.out.printf(" [%d][%d] = ",i,j);

number[i][j]= input.nextInt();

}

}

input.close();

//PRINT THE 2D ARRAY OF number
System.out.println("\nPRINT int [][] number\n");

//int size =number.length;
//System.out.print(size);

for(int i=0; i() { //Test:
@Override
public int compare(String[] s1, String[] s2) {

for (int i = 0; i < s1.length; i++) {

if (s2.length == i) return 1;

int comp = s1[i].compareTo(s2[i]);

if (comp != 0)
return comp;
}
return -1;
}
});

//PRINT SORTED ARRAY
System.out.println("\nSORTED ARRAY DERIVED FROM String [][] str \n");

for(int i=0; i<str.length; i++) {
for (int j = 0; j<str[i].length; j++) {

System.out.printf("%5s", str[i][j]);

}
System.out.println();
}

}

}

8. how to sort two array character with ascending order ex : ['a','c','e'] ['b','d','e'] op:[a,b,c,d,e] please give me the logical

9. import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

/**SORTING 2D ARRAY, by John Kerry Omoti, Lagos, Nigeria. **/

public class SortingArrays {

public static void main(String[] args) {

//INPUT ELEMENTS OF THE 2D ARRAY
System.out.println("\nENTER INPUT ELEMENTS FOR int [][] number\n")
;
Scanner input = new Scanner (System.in);

int [][] number = new int ;

for (int i = 0; i <3; i++) {

for (int j = 0; j < 4; j++) {

System.out.printf(" [%d][%d] = ",i,j);

number[i][j]= input.nextInt();

}

}

input.close();

//PRINT THE 2D ARRAY OF number
System.out.println("\nPRINT int [][] number\n");

//int size =number.length;
//System.out.print(size);

for(int i=0; i() { //Test:
@Override
public int compare(String[] s1, String[] s2) {

for (int i = 0; i < s1.length; i++) {

if (s2.length == i) return 1;

int comp = s1[i].compareTo(s2[i]);

if (comp != 0)
return comp;
}
return -1;
}
});

//PRINT SORTED ARRAY
System.out.println("\nSORTED ARRAY DERIVED FROM String [][] str \n");

for(int i=0; i<str.length; i++) {
for (int j = 0; j<str[i].length; j++) {

System.out.printf("%5s", str[i][j]);

}
System.out.println();
}

}

}

10. import java.util.Scanner;

public class Main {

public static void insertionSort(int arr[]){
int n= arr.length,i,j,p,temp;
for(i=1;i=0 && arr[j+1]< arr[j];j--){
temp = arr[j+1];
arr[j+1]=arr[j];
arr[j]=temp;

}
}
}

public static void printInDisplay(int arr[]){

for(int i=0;i< arr.length;i++){
System.out.println(arr[i]+" ");
}
}

public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("how much number want to store in array?\n");
int n = input.nextInt();
int arr [] = new int[n];
System.out.println("enter array element\n");
for(int i=0; i<n;i++){
arr[i]= input.nextInt();
}
System.out.println("entered elements are:\n");
printInDisplay(arr);
insertionSort(arr);
System.out.println("Sort with Insertion Sort:\n");
printInDisplay(arr);
}
}

11. import java.util.Scanner;

public class Main {

public static void insertionSort(int arr[]){
int n= arr.length,i,j,p,temp;
for(i=1;i=0 && arr[j+1]< arr[j];j--){
temp = arr[j+1];
arr[j+1]=arr[j];
arr[j]=temp;

}
}
}

public static void printInDisplay(int arr[]){

for(int i=0;i< arr.length;i++){
System.out.println(arr[i]+" ");
}
}

public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("how much number want to store in array?\n");
int n = input.nextInt();
int arr [] = new int[n];
System.out.println("enter array element\n");
for(int i=0; i<n;i++){
arr[i]= input.nextInt();
}
System.out.println("entered elements are:\n");
printInDisplay(arr);
insertionSort(arr);
System.out.println("Sort with Insertion Sort:\n");
printInDisplay(arr);
}
}

12. Hi, If i have 15000 arrays and each array contains 5 elements, i want to display each array elements in ascending order. please help with this.

Feel free to comment, ask questions if you have any doubt.