![]() |
sorting in java |
There are several algorithms which are useful to sort according to the characteristic of the data. ex merge sort and quick sort have same time complexity Ω(n log(n)). The worst-case complexity of quicksort is O(n2) while the complexity of mergesort is Ω(n log(n)).
![]() |
implementation is time taking |
It is not possible to write whole sorting implementation in our programmer if you are doing competitive programming. It is time-wasting and time is important for everyone.
Arrays class has the sort() method for the same task "sorting". Internally it is using a dual-pivot quicksort algorithm to sort primitive types of arrays.
sort an integer array in ascending order
int[] arr1 = {5,6,2,4,3,8,10 };
Arrays.sort(arr1);
for(int ele : arr1)
System.out.print(ele+ " ");
output --> 2 3 4 5 6 8 10
sort subarray of an array
int[] arr1 = {5,6,2,4,3,8,10 };
//second arg is starting index of sub-array which is included in sorting
//third arg is ending index of sub-array which is excluded in sorting
Arrays.sort(arr1,1,4);
for(int ele : arr1)
System.out.print(ele+ " ");
output --> 5 2 4 6 3 8 10
//second arg is starting index of sub-array which is included in sorting
//third arg is ending index of sub-array which is excluded in sorting
Arrays.sort(arr1,1,4);
for(int ele : arr1)
System.out.print(ele+ " ");
output --> 5 2 4 6 3 8 10
![]() |
reverse sorting |
sort an integer array in descending order
int[] arr1 = {5,6,2,4,3,8,10 };
Arrays.sort(arr1);
for(int ele : arr1)
System.out.print(ele+ " ");
output --> error: no suitable method found for sort(int[],Comparator)
so,Arrays.sort(arr1);
for(int ele : arr1)
System.out.print(ele+ " ");
output --> error: no suitable method found for sort(int[],Comparator)
Integer[] arr1 = {5,6,2,4,3,8,10 };
Arrays.sort(arr1,Collections.reverseOrder());
for(int ele : arr1)
System.out.print(ele+ " ");
output --> 10 8 6 5 4 3 2
Arrays.sort(arr1,Collections.reverseOrder());
for(int ele : arr1)
System.out.print(ele+ " ");
output --> 10 8 6 5 4 3 2
March 05, 2020
Tags :
Algorithm
Subscribe by Email
Follow Updates Articles from This Blog via Email
No Comments
Please comment here...