1Here’s the java program to sort an array using Arrays.sort() method.
2
3import java.util.Arrays;
4public class JavaArraySortMethod
5{
6 public static void main(String[] args)
7 {
8 String[] strGiven = {"Great Barrier Reef", "Paris", "borabora", "Florence","tokyo", "Cusco"};
9 Arrays.sort(strGiven);
10 System.out.println("Output(case sensitive) : " + Arrays.toString(strGiven));
11 }
12}
1// how to sort an array in java without using sort() method (ascending order)
2public class WithoutSortMethod
3{
4 public static void main(String[] args)
5 {
6 int temp;
7 int[] arrNumbers = {14, 8, 5, 54, 41, 10, 1, 500};
8 System.out.println("Before sort: ");
9 for(int num : arrNumbers)
10 {
11 System.out.println(num);
12 }
13 for(int a = 0; a < arrNumbers.length; a++)
14 {
15 for(int b = a + 1; b < arrNumbers.length; b++)
16 {
17 if(arrNumbers[a] > arrNumbers[b])
18 {
19 temp = arrNumbers[a];
20 arrNumbers[a] = arrNumbers[b];
21 arrNumbers[b] = temp;
22 }
23 }
24 }
25 System.out.println("---------------");
26 System.out.println("After sort: ");
27 for(int num : arrNumbers)
28 {
29 System.out.println(num);
30 }
31 }
32}
1// how to sort an array in java without using sort method
2public class WithoutUsingSortMethod
3{
4 public static void main(String[] args)
5 {
6 int temp;
7 int[] arrNumbers = {14, 8, 5, 54, 41, 10, 1, 500};
8 System.out.println("Before sort: ");
9 for(int num : arrNumbers)
10 {
11 System.out.println(num);
12 }
13 for(int a = 0; a <= arrNumbers.length - 1; a++)
14 {
15 for(int b = 0; b <= arrNumbers.length - 2; b++)
16 {
17 if(arrNumbers[b] < arrNumbers[b + 1])
18 {
19 temp = arrNumbers[b];
20 arrNumbers[b] = arrNumbers[b + 1];
21 arrNumbers[b + 1] = temp;
22 }
23 }
24 }
25 System.out.println("---------------");
26 System.out.println("After sort: ");
27 for(int num : arrNumbers)
28 {
29 System.out.println(num);
30 }
31 }
32}
1// how to sort an array of strings in descending
2import java.util.Arrays;
3import java.util.Collections;
4public class SortStringAlphabeticalOrder
5{
6 public static void main(String[] args)
7 {
8 String[] strDesc = {"Bear","Fox","Deer","Cheetah","Anteater","Elephant"};
9 System.out.println("Before sorting: ");
10 for(String string : strDesc)
11 {
12 System.out.println(string);
13 }
14 // arrays.sort
15 Arrays.sort(strDesc, Collections.reverseOrder());
16 System.out.println("-----------------------------------");
17 System.out.println("Sorting string array in descending or reverse order: ");
18 for(String string : strDesc)
19 {
20 System.out.println(string);
21 }
22 }
23}