Sorting an array in ascending or descending order.
Here’s an example of a Java program that sorts an array in either ascending or descending order based on user input:
import java.util.Arrays; import java.util.Scanner; public class ArraySorter { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Read array size from user System.out.print("Enter the size of the array: "); int size = scanner.nextInt(); // Create array int[] array = new int[size]; // Read array elements from user System.out.println("Enter the elements of the array:"); for (int i = 0; i < size; i++) { System.out.print("Element " + (i + 1) + ": "); array[i] = scanner.nextInt(); } // Prompt user for sorting order System.out.print("Enter 'A' for ascending order or 'D' for descending order: "); String sortOrder = scanner.next(); // Sort the array based on the user's choice if (sortOrder.equalsIgnoreCase("A")) { Arrays.sort(array); // Sort in ascending order } else if (sortOrder.equalsIgnoreCase("D")) { Arrays.sort(array); // Sort in ascending order first // Reverse the array to get descending order for (int i = 0; i < size / 2; i++) { int temp = array[i]; array[i] = array[size - 1 - i]; array[size - 1 - i] = temp; } } else { System.out.println("Invalid input. Exiting the program."); return; } // Display the sorted array System.out.println("Sorted array in " + (sortOrder.equalsIgnoreCase("A") ? "ascending" : "descending") + " order:"); for (int num : array) { System.out.print(num + " "); } } }
In this program, we first read the size of the array from the user. Then we create the array and read its elements. Next, the program prompts the user to enter ‘A’ for ascending order or ‘D’ for descending order. Based on the user’s choice, the array is sorted using the `Arrays.sort()` method for ascending order. If the user chooses descending order, we first sort the array in ascending order and then reverse it manually. Finally, the sorted array is displayed to the user.
No comments yet! You be the first to comment.