Q-09: Write a JAVA program to sort a given Array in Ascending Order and Descending Order.
    

Ascending Order


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

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; class DescendingOrder { public static void display(int arr[ ], int size) { for(int i=0; i < size; i++) { System.out.print(arr[i]+" "); } System.out.println(""); } public static void main(String[ ] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter the size of the Array: "); int size = sc.nextInt(); int [ ]arr = new int[size]; System.out.println("Enter "+size+" Elements:"); for(int i=0; i < size; i++) { arr[i] = sc.nextInt(); } System.out.println(""); display(arr,size); // Sorting in Descending Order! for(int i=0; i < size-1; i++) { for(int x=0; x < size-1-i; x++) { if(arr[x] < arr[x+1]) { int temp = arr[x]; arr[x] = arr[x+1]; arr[x+1] = temp; } } } display(arr,size); } }

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