212k views
0 votes
Create a Java application using arrays that sorts a list of integers in descending order. For example, if an array has values 106, 33, 69, 52, 17 your program should have an array with 106, 69, 52, 33, 17 in it. It is important that these integers be read from the keyboard. Implement the following methods – getIntegers, printArray and sortIntegers. • getIntegers returns an array of entered integers from the keyboard. • printArray prints out the contents of the array • sortIntegers should sort the array and return a new array contained the sorted numbers

User Matias Vad
by
7.5k points

1 Answer

3 votes

Answer: import java.util.Arrays;

import java.util.Scanner;

public class SortIntegers {

public static void main(String[] args) {

int[] originalArray = getIntegers();

System.out.print("Original array: ");

printArray(originalArray);

int[] sortedArray = sortIntegers(originalArray);

System.out.print("Sorted array in descending order: ");

printArray(sortedArray);

}

public static int[] getIntegers() {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of integers: ");

int n = scanner.nextInt();

int[] array = new int[n];

System.out.print("Enter " + n + " integers: ");

for (int i = 0; i < n; i++) {

array[i] = scanner.nextInt();

}

return array;

}

public static void printArray(int[] array) {

for (int i = 0; i < array.length; i++) {

System.out.print(array[i] + " ");

}

System.out.println();

}

public static int[] sortIntegers(int[] array) {

int[] sortedArray = Arrays.copyOf(array, array.length);

Arrays.sort(sortedArray);

for (int i = 0; i < sortedArray.length / 2; i++) {

int temp = sortedArray[i];

sortedArray[i] = sortedArray[sortedArray.length - 1 - i];

sortedArray[sortedArray.length - 1 - i] = temp;

}

return sortedArray;

}

}

Explanation: The following elucidates the operational mechanism of the program:

The method named getIntegers prompts the user to enter the desired quantity of integers to be inputted, followed by the inputting of integers from the keyboard, with the resultant integers being returned as an array data structure.

The printArray function accepts an array as an argument and outputs the array's elements.

The sorterIntegers function generates a duplicate of the input array through the usage of the Arrays.copyOf method, proceeds to sort this array in ascending order utilizing the Arrays.sort method, and subsequently performs a fundamental swap operation to invert the placement of the elements, thereby achieving the targeted descending order. Subsequent to the sorting process, the array is subsequently relinquished.

In the principal procedure, the software invokes getIntegers to retrieve the input array, produces its contents with printArray, sorts the array via sortIntegers, and displays the ordered array using printArray.