How to sort elements in a list in ALGOL?
Sorting a list sequentially in ALGOL can be achieved through multiple algorithms but the most commonly used approach is the Bubble sort convention. Here are the steps detailing how you can sort a list in ALGOL using bubble sort.
Step 1:
Begin by defining the list that needs to be sorted. In ALGOL, you can define a list as a one-dimensional array. Make sure the list has been initialized properly with the desired elements.
BEGIN
INTEGER ARRAY list[1:5];
list[1] := 5;
list[2] := 3;
list[3] := 4;
list[4] := 1;
list[5] := 2;
Step 2:
Implement the Bubble sort algorithm. Bubble sort works by repeatedly swapping the adjacent elements if they are in the wrong order.
INTEGER i, j, tmp;
FOR i := 1 STEP 1 UNTIL 5 DO
FOR j := 1 STEP 1 UNTIL 4 DO
IF list[j] > list[j+1] THEN
BEGIN
tmp := list[j];
list[j] := list[j+1];
list[j+1] := tmp;
END;
This part of the code initializes two loops; the outer loop (with 'i') traverses through the entire list for the number of elements present. The inner loop (with 'j') compares each element with the next one. If the current element (list[j]) is bigger than the next element (list[j+1]), they are swapped.
Step 3:
Finally, you should display your list that has now been sorted. You can loop through your sorted list and print the elements. Once the program runs, it will display all the elements of your sorted list.
FOR i := 1 STEP 1 UNTIL 5 DO
PRINT(list[i]);
END
This entire program sorts your list in ascending order. It implements the Bubble Sort technique in ALGOL to first sort your list and then finally print the sorted list.