Page 87 - CTS - CSA TP - Volume 2
P. 87
COMPUTER SOFTWARE APPLICATION - CITS
System.out.println(numbers[i]);
}
scanner.close(); // Close the scanner to avoid resource leak
}
}
Output:
Explanation:
• This program is quite similar to the previous one but with an additional step to sort the array elements
before displaying them.
• It imports the Arrays class from the java.util package, which provides a method sort() to sort arrays.
• After reading all the elements, it uses Arrays.sort(numbers) to sort the array in ascending order.
• Then, it displays the sorted array elements using a loop.
• Finally, it closes the Scanner object to release system resources.
This program allows the user to input array elements dynamically and displays them in sorted order.
Method 2:Java program that sorts n elements in descending order using the bubble sort method:
Let’s see with an example. Here, each step is briefly illustrated:
Bubble sort algorithm is an algorithm that sorts an array by comparing two adjacent elements and swapping
them if they are not in the intended order. Here order can be anything like increasing or decreasing.
Let’s see with an example. Here, each step is briefly illustrated:
72
CITS : IT & ITES - Computer Software Application - Exercise 93