Pascal language - Recursion within a Bubble Sort

December 2016




Intro


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


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).

Example


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;


Thanks to Zouari Lazhar for this tip.

Related :

This document entitled « Pascal language - Recursion within a Bubble Sort » from CCM (ccm.net) is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.