0

Here's a c++ code to sort the data of various types using template function. Can someone elaborate what does BOOL do here? I've read about bool data type. It basically assumes only two values TRUE and FAlSE. But I've no idea, what is the role of BOOL here ?

   using namespace std;
    #include <iostream>
    
      template <class T>
      void sort (T array[], int size)
      { int j;
        T temp;
        int pass;
        static int call = 0;
        bool xchange = true;
        for (pass = 1; pass < size && xchange == true; pass++)
        { xchange = false;
          for (j=0; j < size - pass; j++)
          { if (array[j] > array[j+1])
            { temp = array[j]; array[j] = array[j+1]; array[j+1] = temp;
              xchange = true;
            } /* end of if */
          } /* end of inner for loop */
        };
        call ++;
        cout << " within sort : value of call is " << call << endl;
        /* end of outer for loop */
       } /* end of bubble sort */
    
      int main() {
       int a[] = {1,5,6,4,0,8,5,7,9,2};
       int a1[] = {1,5,6,4,0,8,5,7,9,2};
       char b[] = { 'a', 'c', 'f', 'd', 'b' };
      
       sort (a, 10);
       for ( int i=0; i < 10; i++ ) cout << a[i] << "  ";
       cout << endl;
       sort (b, 5);
       for ( int i=0; i < 5; i++ ) cout << b[i] << "  ";
       cout << endl;
       sort (a1, 10);
       for ( int i=0; i < 10; i++ ) cout << a1[i] << "  ";
       cout << endl;
       
       return 0;
      }
Mathaddict
  • 135
  • 6

1 Answers1

0

The bool in the example is there to check wether any exchanges happened in that iteration of the for-loop. If no exchanges happened == the array is sorted, the sorting algorithm is done. Giving this function a already sorted array will show the purpose of the boolean. In the first iteration through the whole array, no exchanges will take place (because the array is already sorted) -> the xchange was never set to true -> the sorting algorithm is done == the condition in the for-loop condition is false. It is there to not do work that you dont have to do.

  • What @largest_prime_is_463035818 mentioned is that the bool makes everything a little bit confusing, using a break might clear that up. Check out [link] (https://stackoverflow.com/questions/3922599/is-it-a-bad-practice-to-use-break-in-a-for-loop) – Markus Schmidt Mar 22 '21 at 12:20