- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to sort Java array elements in ascending order?
To sort an array in Java, you need to compare each element of the array to all the remaining elements and verify whether it is greater if so swap them.
One solution to do so you need to use two loops (nested) where the inner loop starts with i+1 (where i is the variable of outer loop) to avoid repetitions in comparison.
Example
import java.util.Arrays; import java.util.Scanner; public class ArrayInOrder { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter the size of the array that is to be created::"); int size = sc.nextInt(); int[] myArray = new int[size]; System.out.println("Enter the elements of the array ::"); for(int i = 0; i<size; i++) { myArray[i] = sc.nextInt(); } for(int i = 0; i<size-1; i++) { for (int j = i+1; j<myArray.length; j++) { if(myArray[i] > myArray[j]) { int temp = myArray[i]; myArray[i] = myArray[j]; myArray[j] = temp; } } } System.out.println(Arrays.toString(myArray)); } }
Output
You can also sort an array using the sort() method of the Arrays class.
int[] myArray = {12, 56, 78, 90, 123, 75, 897}; Arrays.sort(myArray); System.out.println(Arrays.toString(myArray));
- Related Articles
- Java Program to Sort Array list in an Ascending Order
- Python program to sort the elements of an array in ascending order
- C++ Program to Sort the Elements of an Array in Ascending Order
- Swift Program to Sort the Elements of an Array in Ascending Order
- Golang Program To Sort The Elements Of An Array In Ascending Order
- C program to sort an array of ten elements in an ascending order
- How to sort an ArrayList in Java in ascending order?
- How to sort an ArrayList in Ascending Order in Java
- Golang Program To Sort An Array In Ascending Order Using Insertion Sort
- Swift Program to sort an array in ascending order using bubble sort
- Swift Program to sort an array in ascending order using selection sort
- Swift Program to sort an array in ascending order using quick sort
- 8086 program to sort an integer array in ascending order
- C program to sort an array in an ascending order
- Java Program to Sort the Array Elements in Descending Order

Advertisements