Sort an Array Elements in Java
Advertisements
Sort an Array Elements in Java
To sort array element in java no need to write new concept just change the syntax of c programming into java code..
Sort an Array Elements in Ascending Order in Java
import java.util.Scanner; public class SortArray { public static void main(String[] args) { int n, temp; Scanner s = new Scanner(System.in); System.out.print("Enter no. of elements you want in array:"); n = s.nextInt(); int a[] = new int[n]; System.out.println("Enter all the elements:"); for (int i=0; i<n; i++) { a[i]=s.nextInt(); } for (int i =0; i<n; i++) { for (int j=i+1; j<n; j++) { if (a[i]>a[j]) // compare numbers { temp=a[i]; a[i]=a[j]; a[j]=temp; } } } System.out.print("Elements in Ascending Order:"); for (int i=0; i<n-1; i++) { System.out.print(a[i]+ ", "); // print in same line and separate with comma } System.out.print(a[n-1]); } }
Output
Enter no. of elements you want in array: 5 3 4 1 7 6 Elements in Ascending Order: 1, 3, 4, 6, 7
Syntax to compile and run java program
Syntax
for compile -> c:/>javac SortArray.java for run -> c:/>java SortArray
Explanation of Code
- Scanner s=new Scanner(System.in): are used for receive input from keyboard.
- nextInt(): method are used for get integer type value from keyboard.
- System.out.println("....."): are used for display message on screen or console.
Google Advertisment