Explanation
The provided Java code implements the Bubble Sort algorithm, which is one of the simplest sorting techniques. The core idea is to repeatedly step through the list, compare adjacent elements, and swap them if they are in the wrong order. This process repeats until the entire array is sorted.
- Initialization: The program starts with an unsorted array of integers:
{5, 1, 12, 2, 8}. - Outer Loop: This loop runs $n-1$ times. Each pass through the outer loop ensures that the next largest element "bubbles up" to its correct position at the end of the array.
- Inner Loop: This loop performs the actual comparisons. It compares the element at index
jwith the one atj + 1. The limitn - 1 - iis used because, after each pass of the outer loop, the largest elements are already sorted at the end, so we don't need to check them again. - Swapping: If the element on the left (
arr[j]) is greater than the element on the right (arr[j+1]), they are swapped using a temporary variable (temp). - Optimization (The
swappedflag): A boolean variableswappedis initialized tofalseat the start of each outer pass. If a swap occurs, it becomestrue. If the inner loop finishes and no swaps happened, it means the array is already sorted, and the program breaks out of the loop early to save time. - Output: Finally, the program uses an enhanced for-loop to print the sorted elements to the console.