top of page
Search

Practical use case: Sorting arrays

  • Writer: Ivaylo Fiziev
    Ivaylo Fiziev
  • May 30
  • 2 min read

How do you arrange the elements of an array in ascending/descending order? This trivial problem has an even more trivial solution - you use a sorting algorithm. There are a number of these algorithms. They differ in terms of complexity (O notation) and therefore make the process faster or slower. To mention a few: bubble sort, quick sort etc.

In this post I will showcase the usage of the slowest one among all algorithms - bubble sort (https://en.wikipedia.org/wiki/Bubble_sort). Why the slowest one? It is usually the one showcased first because of its simplicity.

So how does it work? It compares each two elements of the array, swapping them if necessary. The process repeats itself until all elements are compared. This is what makes it slow ...

In terms of code it looks like this:

FUNCTION_BLOCK "MAIN"
VERSION:1.0
VAR
	// array to sort
	arr : Array [1..10] of INT := [10,-10,5,-5,3,-3,2,-2,0,1];
END_VAR
VAR_TEMP
	swap : BOOL;		// swap indication
	tmp  : INT;		// temporary element for the swap
	n : INT := 10;	// number of elements
	i : INT;			// element index
END_VAR
BEGIN
    repeat
		#swap:= false;
		// sort the array (ascending)
		for #i := 1 to #n-1 do	
			if #arr[#i] > #arr[#i+1] then
				#tmp := #arr[#i];
				#arr[#i] := #arr[#i+1];
				#arr[#i+1] := #tmp;
				#swap:= true;
			end_if;
		end_for;
		#n := #n-1;
	until not #swap
	end_repeat;
END_FUNCTION_BLOCK

When you look at this code, a natural thing to do is to make it work for arrays of different sizes. e.g. make a function out of this. The function however should allow inputs of different types (VARIANT) or arrays of any size (Array[*]). Unfortunately we don't support them yet. This would be a logical next step. Until then algorithms like this should be handled case by case.


See you!


Hint: You can use the SCL debugger to trace the code and see the array being sorted.


 
 
 

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating

Subscribe Form

Thanks for submitting!

bottom of page