Arrays
Sort arrays example
This is an example of how to sort arrays. We are using anint array in the example, but the same API applies to any type of arrays e.g.byte[],char[],double[],float[],long[],short[]. Sorting an int array implies that you should:
- Create an
intarray with elements. - Invoke
sort(int[] a)API method ofArrays. It sorts an array in ascending order based on quicksort algorithm. - We can fully sort an array by using
sort(array)method ofArrays or we can partially sort an array by usingsort(array, startIndex, endIndex)API method of Arrays wherestartIndexis inclusive andendIndexis exclusive. We can print the array’s elements before and after sorting in order to check the elements’ sorting.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core;import java.util.Arrays; public class SortArrayExample { public static void main(String[] args) { /*Please note that the same API applies to any type of arrays e.g. byte[], char[], double[], float[], long[], short[] */ // Create int array int intArray[] = {1,4,3,5,2}; System.out.print("Array prior sorting :"); for(int i=0; i< intArray.length ; i++)System.out.print(" " + intArray[i]); /* Arrays.sort() method sorts an array in ascending order based on quicksort algorithm. We can fully sort an array by using Arrays.sort(array) operation or we can partially sort an array by using Arrays.sort(array, startIndex, endIndex) operation where startIndex is inclusive and endIndex is exclusive */ Arrays.sort(intArray); System.out.print("nArray after full sort :"); for(int i=0; i< intArray.length ; i++)System.out.print(" " + intArray[i]); }}Output:
Array prior sorting : 1 4 3 5 2Array after full sort : 1 2 3 4 5
This was an example of how to sort an array in Java.
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!
We will contact you soon.
Ilias Tsagklis
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor atJava Code Geeks.



