Search code examples
c++bubble-sort

What this lines in bubble sort algorithm means?


In Introduction to programming with C++ 6th edition book, it explain the bubble sort algorithm with C++ and i understand it, but there is two lines of code I'm not understand why they in the code, when I tried to understand code I erase them and nothing changed and the algorithm still working. So I still confused about them. there is the code;

int main()
 {
     int numbers[4] = {23, 46, 12, 35};
     int sub = 0; //keeps track of subscripts
     int temp = 0; //variable used for swapping
     int maxSub = 3; //maximum subscript
     int lastSwap = 0; //position of last swap
     char swap = 'Y'; //indicates if a swap was made

     //repeat loop instructions as long as a swap was made
     while (swap == 'Y')
     {
     swap = 'N'; //assume no swaps are necessary

     sub = 0; //begin comparing with first
     //array element

     //compare adjacent array elements to determine
     //compare adjacent array elements to determine
     //whether a swap is necessary
     while (sub < maxSub)
     {
         if (numbers[sub] > numbers[sub + 1])
         {
             //a swap is necessary
             temp = numbers[sub];
             numbers[sub] = numbers[sub + 1];
             numbers[sub + 1] = temp;
             swap = 'Y';
             lastSwap = sub;
         } //end if
         sub += 1; //increment subscript
         } //end while

         maxSub = lastSwap; //reset maximum subscript
     } //end while

     //display sorted array
     for (int x = 0; x < 4; x += 1)
        cout << numbers[x] << endl;
     //end for

     system("pause");
     return 0;
 } //end of main function 

so I don't understand lastSwap = sub & maxSub = lastSwap. are they important or I'm right about erase them from the code? can anyone explain to it to me.


Solution

  • To keep it simple,

    1st pass of Bubble Sort => Maximum element in array gets the new appropriate position.

    2nd pass => Second maximum element in array gets the new appropriate position.

    .

    .

    .

    Nth pass => Nth element in array gets the new appropriate position.

    Variable lastSwap stores the maximum index of the array where the last swapping occurred.

    Now, if for the first pass, the new appropriate position is not the last index of the array, that is, lastSwap < last index of array, then it means that the array after the index lastSwap is already sorted and we don't need to process it.

    This is followed for each pass and upper bound on total number of passes(maxSub) is set to lastSwap, thus reducing the number of passes.

    Advantages of using those 2 lines:

    1. We optimised the number of passes when the array gets sorted before the completion of all passes.

    2. It can also detect if the given / input array is sorted or not, in the first pass.