Explanation
The provided Java code demonstrates how to sort an array of integers in descending order (from largest to smallest).
The logic uses two nested for loops, a technique often referred to as an "Exchange Sort" or a variation of "Selection Sort."
- Initialization: An integer array
arris created with five unsorted values:{5, 2, 8, 1, 9}. - Outer Loop: The first loop (variable
i) starts at the beginning of the array. Its job is to "fix" the value for the current positioni. - Inner Loop: The second loop (variable
j) starts from the position immediately afteri(i + 1) and scans the rest of the array. - Comparison and Swapping: Inside the inner loop, the code compares the element at index
iwith the element at indexj. Since we want a descending order, the conditionif (arr[i] < arr[j])checks if the current element is smaller than any subsequent element. If it is, they swap places. This ensures that after the inner loop finishes one full cycle, the largest available number is moved to positioni. - Temporary Variable: A variable named
tempis used during the swap to prevent data loss. It holds the value ofarr[i]whilearr[j]is moved intoarr[i]. - Output: Finally, an "enhanced for-loop" (also known as a for-each loop) iterates through the modified array and prints each number to the console.