COBOL Bubble Sort with Optimization
IDENTIFICATION DIVISION. PROGRAM-ID. BUBBLE-SORT-OPTIMIZED. AUTHOR. Admin. DATA DIVISION. WORKING-STORAGE SECTION. 01 NUMBERS-TABLE. 05 NUMBERS OCCURS 10 TIMES INDEXED BY IDX-NUMBERS PIC 9(4) VALUE 0. 01 SWAPPED-FLAG PIC X VALUE 'N'. 88 SWAPPED VALUE 'Y'. 88 NOT-SWAPPED VALUE 'N'...
This COBOL program implements an optimized Bubble Sort algorithm to sort an array of integers in ascending order. It includes a flag to detect if any swaps occurred in a pass, allowing for early termination if the array...
The Bubble Sort algorithm repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The optimization implemented here uses a `SWAPPED-FLAG` to check if any swaps were made during a pass. If no swaps occur, it means the array is already sorted, and the algorithm terminates early. The outer loop runs at most N-1 times, and the inner loop compares adjacent elements. In the worst case, where the array is in reverse order, the time complexity is O(N^2). In the best case, with the optimization, if the array is already sorted, it's O(N). The space complexity is O(1) as it only uses a few extra variables for swapping and control. Edge cases handled include an empty array (N=0, loops won't execute) and a single-element array (N=1, loops won't execute). The algorithm guarantees correctness because each pass moves the largest unsorted element to its correct final position.
PROCEDURE BUBBLE-SORT-OPTIMIZED: SET SWAPPED-FLAG to TRUE DECREMENT N by 1 LOOP I from 1 to N: SET SWAPPED-FLAG to FALSE LOOP J from 1 to N - I: IF element at J > element at J+1: SWAP elements at J and J+1 SET SWAPPED-FL...