Q-11: Write a JAVA program to sort a given List of numbers in Ascending Order and Descending Order (Using ArrayList from Collection Framework).
    

Ascending Order


// Contributed by - Anuj Das ( GC College, Silchar - @ Department of Computer Science ) import java.util.Scanner; import java.util.ArrayList; class AscendingOrder { static void display(ArrayList<Integer> list) { for(int i=0; i < list.size(); i++){ System.out.print(list.get(i)+" "); } System.out.print("\n"); } public static void main(String[] args) { Scanner input = new Scanner(System.in); ArrayList<Integer> list = new ArrayList<>(); System.out.print("Enter the size of the Array: "); int size = input.nextInt(); System.out.println("Enter "+size+" Elements: "); for(int i=0; i < size; i++){ list.add(input.nextInt()); } display(list); // Sorting in Ascending Order! int n = list.size(); for(int i=0; i < n-1; i++) { for(int j=0; j < n-1-i; j++) { if(list.get(j) > list.get(j+1)) { Integer temp; temp = list.get(j); list.set(j, list.get(j+1)); list.set(j+1, temp); } } } display(list); } }

OUTPUT

cmd->  javac  AscendingOrder.java
cmd->  java  AscendingOrder

Enter the size of the Array:  5
Enter 5 Elements:
45
10
20
12
11

45  10  20  12  11
10  11  12  20  45


    

Descending Order


// Contributed by - Anuj Das ( GC College, Silchar - @ Department of Computer Science ) import java.util.Scanner; import java.util.ArrayList; class DescendingOrder { static void display(ArrayList<Integer> list) { for(int i=0; i < list.size(); i++){ System.out.print(list.get(i)+" "); } System.out.print("\n"); } public static void main(String[] args) { Scanner input = new Scanner(System.in); ArrayList<Integer> list = new ArrayList<>(); System.out.print("Enter the size of the Array: "); int size = input.nextInt(); System.out.println("Enter "+size+" Elements: "); for(int i=0; i < size; i++){ list.add(input.nextInt()); } display(list); // Sorting in Descending Order! int n = list.size(); for(int i=0; i < n-1; i++) { for(int j=0; j < n-1-i; j++) { if(list.get(j) < list.get(j+1)) { Integer temp; temp = list.get(j); list.set(j, list.get(j+1)); list.set(j+1, temp); } } } display(list); } }

OUTPUT

cmd->  javac  DescendingOrder.java
cmd->  java  DescendingOrder

Enter the size of the Array:  6
Enter 6 Elements:
45
12
10
15
35
24

45  12  10  15  35  24
45  35  24  15  12  10