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}
1public class SortingData {
2 public static void main(String[] args)
3 {
4 int[] arr = { 13, 7, 6, 45, 21, 9, 101, 102 };
5
6 Arrays.sort(arr);//sort() function
7
8 System.out.printf("Modified arr[] : %s",
9 Arrays.toString(arr));
10 }
11}
1// java sort arraylist
2import java.util.ArrayList;
3import java.util.Collections;
4public class JavaSortArraylist
5{
6 public static void main(String[] args)
7 {
8 ArrayList<String> al = new ArrayList<String>();
9 al.add("Bear");
10 al.add("Fox");
11 al.add("Deer");
12 al.add("Cheetah");
13 al.add("Anteater");
14 al.add("Elephant");
15 System.out.println("Before sorting ArrayList: " + al);
16 Collections.sort(al);
17 System.out.println("After sorting ArrayList in Ascending order: " + al);
18 }
19}
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}