Sort arrays in descending order using Java

For us to understand arrays in Java, we’ll write a small program that sorts a list of integers in descending order. The program uses arrays, and it is expected to sort the values in descending order- from the highest to the lowest value. For instance, if the user of the program passes in these values, 1,10,24,56,90,71,2. The values should be sorted in a descending order, meaning that the output should be 90,71,56,24,10,2,1. The program will be set up in a way that numbers to be sorted are read from the keyboard. In addition, the program implements the following methods, sortIntegers – to sort an array of integers and return a new array that contains sorted numbers. The printArray method to print sorted integers and getIntegers to return an array of numbers entered from the keyboard.


getIntegers method

The method takes one integer value which determines the size of an array and uses for-loop to get integer values from the keyboard and returns an array of integers. Here is a screenshot of the method.

printArray method

The method printArray takes an integer array (int[] arrayValues) as input and prints out each element along with its index. Here is a screenshot of printArray method.

sortIntegers

The method sortIntegers sorts an array of integers in descending order using the bubble sort algorithm. Bubble sort algorithm is good for small and moderate size arrays because it is considered inefficient in large-sized arrays- arrays that hold thousands of values. Here is a screenshot sortIntegers method:

Lessons

This Java program demonstrates several fundamental concepts:

• Array Declaration and Initialization
• User Input
• Printing Arrays
• Sorting Arrays
• Looping – while loops and for loops
• Conditional Statements: Conditional statements if – statements
• Scanner Class - The Scanner class is utilized for taking user input from the console.
The whole code can be downloaded here: Source Code

Also, here is a short video that shows how the program performs

Comments

Popular posts from this blog

Hangman Game With Python

Build a Shopping List Application with ArrayList in Java

File handling with C++ Programming