Sorting in Java means arranging the data of an array or any other collection in a specific order. This helps us find, manipulate, or parse the data of a collection, efficiently. To do that in Java, a built-in sort() method is used. Other than this method, you can also use the traditional sorting algorithms to sort any given array in ascending order.
This blog post will discuss different sorting techniques to order an array in ascending order in Java.
Sorting an Array in Ascending Order in Java
The “sort()” method of the Java “Arrays” class is used to sort/arrange an array. It is a static method of the “java.util.Arrays” class. This method takes an array and sorts/arranges its elements in ascending order. Here is the practical implementation of sort() method in Java:
import java.util.Arrays;
public class SortingArraysJava {
public static void main(String[] args) {
int[] inputArr = new int[] {100, 101, 150, 10, -513, 0, 121, 11 };
System.out.println("Input Array == " + Arrays.toString(inputArr));
Arrays.sort(inputArr);
System.out.println("Sorted Array == " + Arrays.toString(inputArr));
}
}
In this code, we declare an array and initialize/assign it with various integers. After this, we invoke the Arrays.sort() method to sort the declared array in ascending order. From the output, you can clearly observe that the array has been successfully sorted in ascending order:
Note: You can also overload this method with the start and end indexes, in such cases, only a specific part of the array will be sorted.
Sorting an Array in Ascending Order Without Using the sort() Method
Use one of the following sorting algorithms to arrange an array in ascending order(without using the built-in “sort()” method):
- Method 1: Using Bubble Sort
- Method 2: Using Selection Sort
- Method 3: Using Merge Sort
- Method 4: Using Insertion sort
- Method 5: Using Quick sort
Method 1: Using Bubble Sort
In Java, bubble sort is an easy-to-use(convenient) sorting algorithm that sorts the collection (like array, list, etc.) by comparing adjacent elements. It swaps the elements that are placed in the inappropriate /wrong position. This way, the smaller elements bubble up to the top of the collection with each iteration and ultimately the collection gets sorted. In the below code snippet, we use the bubble sort to sort the given array in ascending order:
import java.util.Arrays;
import java.util.Scanner;
public class SortingArraysJava {
public static void sortArray(int[] inputArray) {
int temp = 0;
for (int i = 0; i < inputArray.length; i++)
{
for (int j = i + 1; j < inputArray.length; j++)
{
if (inputArray[i] > inputArray[j])
{
temp = inputArray[i];
inputArray[i] = inputArray[j];
inputArray[j] = temp;
}
}
}
}
public static void main(String[] args) {
Scanner scanInput = new Scanner(System.in);
System.out.print("Input Array Size ==> ");
int inputSize = scanInput.nextInt();
int inputArr[] = new int[inputSize];
System.out.println("Input Array Elements ==> ");
for (int i = 0; i < inputSize; i++) {
inputArr[i] = scanInput.nextInt();
}
sortArray(inputArr);
System.out.println("Sorted Array Using Bubble Sort is == " + Arrays.toString(inputArr));
scanInput.close();
}
}
In the above code,
- We create a method “sortArray()” that takes an “inputArray” as input and sorts it using the bubble sort.
- Within the sortArray() method, we use a nested for loop to traverse/iterate the array and compare adjacent elements.
- Also, we use an if statement to swap the array elements that are in the wrong/incorrect order.
- In the main() method we use the Scanner class to take array elements (that need to be sorted) from the user.
- Finally, we call the sortArray() method to sort the user-entered array in ascending order:
Method 2: Using Selection Sort
The selection sort is a simple and easy-to-use sorting algorithm that sorts the given collection (like an array) by comparing elements. It splits the given array into a sorted subarray (initially empty) and an unsorted subarray (the given array). It finds the lowest/minimum array element and swaps it with the first element of the unsorted subarray. The below code implements the selection sort to sort the user-given integer-type array into ascending order:
import java.util.Arrays;
import java.util.Scanner;
public class SortingArraysJava {
public static void sortArray(int[] inputArray) {
int arrSize = inputArray.length;
for (int i = 0; i < arrSize - 1; i++) {
int leastIndex = i;
for (int j = i + 1; j < arrSize; j++) {
if (inputArray[j] < inputArray[leastIndex]) {
leastIndex = j;
}
}
int temp = inputArray[leastIndex];
inputArray[leastIndex] = inputArray[i];
inputArray[i] = temp;
}
}
public static void main(String[] args) {
Scanner scanInput = new Scanner(System.in);
System.out.print("Input Array Size ==> ");
int inputSize = scanInput.nextInt();
int inputArr[] = new int[inputSize];
System.out.println("Input Array Elements ==> ");
for (int i = 0; i < inputSize; i++) {
inputArr[i] = scanInput.nextInt();
}
sortArray(inputArr);
System.out.println("Sorted Array Using Selection Sort is == " + Arrays.toString(inputArr));
scanInput.close();
}
}
In the above code,
- We create a sortArray() method that accepts an integer array and sorts/arranges its elements via the selection sort.
- Within this method, we use a nested for-loop to locate the minimum/least element in the unsorted array. After this, we swap it with the first element of the unsorted array.
- This process continues until the whole array gets sorted:
Method 3: Using Insertion Sort
The insertion sort algorithm divides the given array into two subarrays: an unsorted and a sorted subarray. This algorithm picks an element from the unsorted sub-array and puts it in the right place in the sorted sub-array. The below code implements this algorithm to sort the user-provided array in ascending order:
import java.util.Arrays;
import java.util.Scanner;
public class SortingArraysJava {
public static void sortArray(int[] inputArray) {
int arrSize = inputArray.length;
for (int i = 1; i < arrSize; i++) {
int key = inputArray[i];
int j = i - 1;
while (j >= 0 && inputArray[j] > key) {
inputArray[j + 1] = inputArray[j];
j--;
}
inputArray[j + 1] = key;
}
}
public static void main(String[] args) {
Scanner scanInput = new Scanner(System.in);
System.out.print("Input Array Size ==> ");
int inputSize = scanInput.nextInt();
int inputArr[] = new int[inputSize];
System.out.println("Input Array Elements ==> ");
for (int i = 0; i < inputSize; i++) {
inputArr[i] = scanInput.nextInt();
}
sortArray(inputArr);
System.out.println("Sorted Array Using Insertion Sort is == " + Arrays.toString(inputArr));
scanInput.close();
}
}
In the above code,
- The sortArray() method implements the insertion sort to sort the input array in ascending order.
- The for loop in the sortArray() method starts iterating from element 1 and keeps iterating until it reaches the last array element.
- An integer-type variable “key” stores the current array element while a variable “j” stores the array element before the current element.
- The while loop examines if “j” is greater than or equal to 0 and also greater than the current element “key”. If yes, it decrements the value of “j” by one to compare the key with the previous element of the sorted subarray.
- Once the appropriate position of the key is found, insert it into the position “j+1”.
- This phenomenon continues until each element gets sorted:
Method 4: Using Quick Sort
The QuickSort algorithm is based on the Divide and Conquer technique. It picks an element as a pivot and partitions/splits the provided array around it. It achieves this by correctly positioning the pivot in the sorted array. In the following code, we use the quick sort algorithm to sort the provided array:
import java.util.Arrays;
import java.util.Scanner;
public class SortingArraysJava {
public static void sortArray(int[] inputArray, int min, int max) {
if (min < max) {
int pivot = splitArray(inputArray, min, max);
sortArray(inputArray, min, pivot - 1);
sortArray(inputArray, pivot + 1, max);
}
}
public static int splitArray(int[] inputArray, int min, int max) {
int pivot = inputArray[max];
int i = min - 1;
for (int j = min; j < max; j++) {
if (inputArray[j] <= pivot) {
i++;
swapElement(inputArray, i, j);
}
}
swapElement(inputArray, i + 1, max);
return i + 1;
}
public static void swapElement(int[] inputArray, int i, int j) {
int temp = inputArray[i];
inputArray[i] = inputArray[j];
inputArray[j] = temp;
}
public static void main(String[] args) {
Scanner scanInput = new Scanner(System.in);
System.out.print("Input Array Size ==> ");
int inputSize = scanInput.nextInt();
int inputArr[] = new int[inputSize];
System.out.println("Input Array Elements ==> ");
for (int i = 0; i < inputSize; i++) {
inputArr[i] = scanInput.nextInt();
}
sortArray(inputArr, 0, inputArr.length -1);
System.out.println("Sorted Array Using Quick Sort is == " + Arrays.toString(inputArr));
scanInput.close();
}
}
In this code,
- First, we create a sortArray() method that accepts three parameters: given array, start index, and end index.
- Within this method, we use the if statement to check if min is less than max (to make sure that there is at least one element in the given array to sort).
- Up next, we call the splitArray() method from the sortArray() method to get the pivot index.
- After getting the pivot index, we recursively call the sortArray() method to sort the split arrays to the left and right of the pivot.
- In the splitArray() function, we use the partitioning technique to rearrange the elements in appropriate positions.
- From the main() method, we invoke the sortArray() method to get the sorted array in ascending order:
Method 5: Using Merge Sort
This algorithm follows the divide-and-conquer technique to sort an array. It splits the given array into subarrays until each subarray shrinks to only one element. Up next, each subarray is sorted using recursion and finally merged to provide a single sorted array:
import java.util.Arrays;
import java.util.Scanner;
public class SortingArraysJava {
public static void sortArray(int[] inputArray) {
if (inputArray.length <= 1) {
return;
}
int mid = inputArray.length / 2;
int[] leftArray = new int[mid];
int[] rightArray = new int[inputArray.length - mid];
System.arraycopy(inputArray, 0, leftArray, 0, mid);
System.arraycopy(inputArray, mid, rightArray, 0, inputArray.length - mid);
sortArray(leftArray);
sortArray(rightArray);
mergeArrays(inputArray, leftArray, rightArray);
}
public static void mergeArrays(int[] mergeArr, int[] leftArr, int[] rightArr) {
int leftIndex = 0;
int rightIndex = 0;
int mergedIndex = 0;
while (leftIndex < leftArr.length && rightIndex < rightArr.length) {
if (leftArr[leftIndex] <= rightArr[rightIndex]) {
mergeArr[mergedIndex++] = leftArr[leftIndex++];
} else {
mergeArr[mergedIndex++] = rightArr[rightIndex++];
}
}
while (leftIndex < leftArr.length)
{
mergeArr[mergedIndex++] = leftArr[leftIndex++];
}
while (rightIndex < rightArr.length) {
mergeArr[mergedIndex++] = rightArr[rightIndex++];
}
}
public static void main(String[] args) {
Scanner scanInput = new Scanner(System.in);
System.out.print("Input Array Size ==> ");
int inputSize = scanInput.nextInt();
int inputArr[] = new int[inputSize];
System.out.println("Input Array Elements ==> ");
for (int i = 0; i < inputSize; i++) {
inputArr[i] = scanInput.nextInt();
}
sortArray(inputArr);
System.out.println("Sorted Array Using Merge Sort is == " + Arrays.toString(inputArr));
scanInput.close();
}
}
In the above code,
- First, the sortArray() function checks if the array length/size is less than or equal to 1; if yes, it means the given array is already sorted. If no, it calculates the middle index of the given array.
- Up next, this function declares a couple of arrays named “leftArray” and “rightArray” to store the left and right halves of the input array into these arrays.
- After this, the sortArray() method is recursively invoked on the leftArray and rightArray. This process continues until each subarray reduces(contains) to one element.
- Finally, the mergeArrays() method is invoked on the “inputArray”, “leftArray”, and “rightArray” to merge the sorted subarrays into one array.
- Within the mergeArrays() method, a while loop is used to traverse both the left and right arrays simultaneously. The loop compares the elements at the current position in both left and right arrays. Consequently, the smaller element is copied to the merged array, and the corresponding index is incremented.
- After this, a couple of more while loops are used to check if there are still some elements left in the left and right array; if yes, copy them to the merged array.
- Finally, from the main() method invoke the sortArray() method to get the sorted array (in ascending order):
How to Sort a Subarray in Ascending Order in Java
To sort a sub-array in ascending order in Java, invoke the sort() method with three parameters: “array name”, “starting index” and the “last index”. As a result, a sub-array from the specified starting index(inclusive) to the last index(exclusive) will be sorted. For instance, in the following code, the given array will be sorted from the second index to the sixth index:
import java.util.Arrays;
public class SortingArraysJava {
public static void main(String[] args) {
int[] inputArr = new int[] {100, 101, 150, 10, -513, 0, 121, 11 };
System.out.println("Input Array == " + Arrays.toString(inputArr));
Arrays.sort(inputArr, 2, 6);
System.out.println("Sorted Array == " + Arrays.toString(inputArr));
}
}
The output confirms that the specified indexes of the given array are successfully sorted:
How to Sort an Array in Descending Order in Java
You can invoke the “Arrays.srot()” method with the “collections.reverseOrder()” method to sort the given array in descending order, as shown below:
import java.util.Arrays;
import java.util.Collections;
public class SortingArraysJava {
public static void main(String[] args) {
Integer[] inputArr = new Integer[] {100, 101, 150, 10, -513, 0, 121, 11 };
System.out.println("Input Array == " + Arrays.toString(inputArr));
Arrays.sort(inputArr, Collections.reverseOrder());
System.out.println("Array Sorted in Reverse Order == " + Arrays.toString(inputArr));
}
}
In this example, we sorted the provided array in reverse/descending order. Also, we print both the original and the reversed arrays on the console which will help you understand the sort() method better:
That’s all about sorting an array in ascending order in Java.
Conclusion
To sort an array in ascending order in Java, use the sort() method or sorting algorithms, like bubble, selection, quick, etc. The sort() is a built-in static method of the “java.util.Arrays” class and is easy to use. This method has a couple of variants. The first one accepts an array as an argument and sorts it in ascending order(by default) while the other one accepts three parameters: an array, starting index, and ending index. As a result, the overloaded variant of the sort() method sorts a subarray. This post has illustrated different sorting techniques to sort an array in Java in ascending order.