what is sorting in java?
Answers
Answer:
Definition: Sorting means to put data in order; either numerically or alphabetically. There are many times when it is necessary to put an array in order from highest to lowest (descending) or vice versa (ascending).
Answer:
Definition: Sorting means to put data in order; either numerically or alphabetically. There are many times when it is necessary to put an array in order from highest to lowest (descending) or vice versa (ascending).
Explanation:
Sorting in Java
There are two in-built methods to sort in Java.
Arrays.Sort() works for arrays which can be of primitive data type also.
// A sample Java program to demonstrate working of
// Arrays.sort().
// It by default sorts in ascending order.
import java.util.Arrays;
public class GFG {
public static void main(String[] args)
{
int[] arr = { 13, 7, 6, 45, 21, 9, 101, 102 };
Arrays.sort(arr);
System.out.printf("Modified arr[] : %s",
Arrays.toString(arr));
}
}
Output:
Modified arr[] : [6, 7, 9, 13, 21, 45, 101, 102]
Collections.sort() works for objects Collections like ArrayList and LinkedList.
// Java program to demonstrate working of Collections.sort()
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Create a list of strings
ArrayList<String> al = new ArrayList<String>();
al.add("Geeks For Geeks");
al.add("Friends");
al.add("Dear");
al.add("Is");
al.add("Superb");
/* Collections.sort method is sorting the
elements of ArrayList in ascending order. */
Collections.sort(al);
// Let us print the sorted list
System.out.println("List after the use of"
+ " Collection.sort() :\n" + al);
}
}
Output:
List after the use of Collection.sort() :
[Dear, Friends, Geeks For Geeks, Is, Superb]
Which sorting algorithm does Java use in sort()?
Previously, Java’s Arrays.sort method used Quicksort for arrays of primitives and Merge sort for arrays of objects. In the latest versions of Java, Arrays.sort method and Collection.sort() uses Timsort.
Which order of sorting is done by default?
It by default sorts in ascending order.
How to sort array or list in descending order?
It can be done with the help of Collections.reverseOrder().