[Pascal language] Recursion within a Bubble Sort
Pascal is a stable, efficient and block-structured programming language. The "type" of variables used in Pascal language is made up of its semantic nature and its range of values, and can be expressed by a type name, an explicit value range, or as combination of both.
An interesting feature is that Pascal supports recursion, a computing tool allowing, a function or procedure within a program, to make calls to itself. Thus provide efficient coding solutions, by eliminating the use of tedious loops.
Here is a recursive procedure that allows a sort of (
n) number of integers using the Bubble Sort method:
Bubble sort is a simple sorting algorithm. It works by constantly stepping through the list to be sorted, comparing two items at a time and swapping them if they are in the wrong order. (each number is compared to the number that follows it, swapping the two neighboring values into right order if necessary in the most inner loop).
Procedure Bubble_sort (var t : TAB; n : integer);
Var i, aux : integer;
Function Sort (t : TAB; n : integer) : Boolean;
Var ok : boolean; i : integer;
Begin
ok := true; i := 1;
Repeat
If t[i + 1] < t[i] Then ok := false
Else i := i + 1;
Until ((Not ok) or (i >= n));
Sort := ok;
End;
Begin
If Not Sort(t, n) Then
Begin
For i := 1 To n - 1 Do
If t[i] > t[i + 1] Then
Begin
aux := t[i];
t[i] := t[i + 1];
t[i + 1] := aux;
End;
Bubble_sort (t, n);
End;
End;