Explanation
Here is a clear breakdown of the Java program:
1. Purpose
This program sorts an array of integers in descending order (from largest to smallest) using a comparison-based sorting algorithm and prints the final sorted array.
2. Key Concepts
- Arrays: Storing and accessing multiple integer values in a single variable.
- Nested
forLoops: Iterating through the array repeatedly to compare pairs of elements. - Variable Swapping: Using a temporary variable (
temp) to exchange two values in memory. - Enhanced
forLoop (For-Each): Traversing and displaying array elements cleanly.
3. Code Walkthrough
-
Array Initialization:
int[] arr = {5, 2, 8, 1, 9};creates an unsorted array of 5 integers. -
Sorting Logic (Nested Loops):
- Outer loop (
i): Picks an index from the beginning to the end. - Inner loop (
j): Compares the element atiwith every element that comes after it (j = i + 1).
- Outer loop (
-
Comparison & Swap:
if (arr[i] < arr[j])checks if a later element is larger than the current element.- If
true, a standard 3-step swap moves the larger number to the left usingtemp.
-
Displaying Results:
Thefor (int num : arr)loop prints each element sequentially after sorting is complete.
4. Output
Array elements in descending order: 9 8 5 2 1