Program in Structured Text (ST) to sort an array of integers using the bubble sort algorithm:

Home » Blog » instrumentation » Program in Structured Text (ST) to sort an array of integers using the bubble sort algorithm:

Here is an example program in Structured Text (ST) to sort an array of integers using the bubble sort algorithm:

VAR
    arr : ARRAY[0..9] OF INT := [4, 2, 8, 5, 1, 9, 3, 6, 7, 0];
    n : INT := 10;  // number of elements in array
    i, j, temp : INT;
END_VAR

// Bubble sort algorithm
FOR i := 0 TO n - 1 DO
    FOR j := 0 TO n - i - 2 DO
        IF arr[j] > arr[j+1] THEN
            // Swap the elements
            temp := arr[j];
            arr[j] := arr[j+1];
            arr[j+1] := temp;
        END_IF
    END_FOR
END_FOR

In this program, the arr variable is an array of integers with 10 elements, and n is the number of elements in the array. We use the bubble sort algorithm to sort the array in ascending order. The outer loop iterates over the elements of the array, and the inner loop iterates over the unsorted portion of the array. If the current element is greater than the next element, the two elements are swapped. After the loops complete, the array will be sorted in ascending order.

Here’s an alternative way to implement the bubble sort algorithm in Structured Text (ST):

VAR
    arr : ARRAY[0..9] OF INT := [4, 2, 8, 5, 1, 9, 3, 6, 7, 0];
    n : INT := 10;  // number of elements in array
    i, j, temp : INT;
    sorted : BOOL := FALSE;
END_VAR

// Bubble sort algorithm
WHILE NOT sorted DO
    sorted := TRUE;
    FOR i := 0 TO n - 2 DO
        IF arr[i] > arr[i+1] THEN
            // Swap the elements
            temp := arr[i];
            arr[i] := arr[i+1];
            arr[i+1] := temp;
            sorted := FALSE;
        END_IF
    END_FOR
END_WHILE

In this version of the program, we add a sorted flag to the variables, which is used to determine whether the array is already sorted. If the array is already sorted, we can exit the loop early to improve performance.

The algorithm itself is the same as before, but the outer loop is now a WHILE loop that continues until the array is sorted. Inside the loop, we set sorted to TRUE at the beginning, and if any swaps are made, we set sorted to FALSE to indicate that the array is not yet fully sorted. If we go through a complete iteration of the inner loop without making any swaps, then the array is already sorted and we can exit the loop.

Leave a Comment

Your email address will not be published. Required fields are marked *