Sorting is a process of arranging elements in particular order. It may be ascending and descending order.
Here, two examples are given to sort the elements using
built in functions.
- · Arrays.sort()
- · Custom comparators
Java Program to sort integers using ‘Arrays.sort()’:
This
program reads the integer array from user. It process it using ‘Arrays.sort()’
function.
Finally, it prints the sorted integers.
Program:
import
java.util.Arrays;
import
java.util.Collections;
import
java.util.Scanner;
public class
SortEg1 {
public static
void main(String[] args) {
Scanner
scanner = new Scanner(System.in);
System.out.print("Enter number of elements: ");
int no =
scanner.nextInt();
int[]
integerArray = new int[no];
for (int i =
0; i < no; i++)
{
System.out.print("Enter element: ");
integerArray[i] = scanner.nextInt();
}
Arrays.sort(integerArray);
System.out.println(Arrays.toString( integerArray));
}
}
Output:
C:\raji\blog>javac SortEg1.java
C:\raji\blog>java SortEg1
Enter number of elements: 5
Enter element: 45
Enter element: 56
Enter element: 9
Enter element: 23
Enter element: 34
[9, 23, 34, 45, 56]
This is a normal sorting.
If you want to sort the data in reverse manner, let us use
the custom comparators.
Java Program to sort the string elements in reverse
order:
This
program reads the number of String elements and input strings from the user. Using
the custom comparator, it sorts in reverse order.
At last, it prints the data.
Program:
import
java.util.Arrays;
import
java.util.Comparator;
import
java.util.Scanner;
public class
CustomSortEg {
public static
void main(String[] args) {
Scanner
scanner = new Scanner(System.in);
System.out.print("Enter number of Strings: ");
int no =
scanner.nextInt();
String[] a =
new String[no];
for (int i =
0; i < no; i++)
{
System.out.print("Enter element: ");
a[i] =
scanner.next();
}
Arrays.sort(a, Comparator.reverseOrder());
System.out.println("Sorting in reverse order");
System.out.println(Arrays.toString(a));
}
}
Output:
C:\raji\blog>javac CustomSortEg.java
C:\raji\blog>java CustomSortEg
Enter number of Strings: 5
Enter element: car
Enter element: van
Enter element: bike
Enter element: truck
Enter element: bus
Sorting in reverse order
[van, truck, car, bus, bike]
That’s all. These are the ways to sort the elements using
built in functions.
No comments:
Post a Comment