Implementing the Bubble Sort

Fortunately implementing the bubble sort is quite easy given our preparation. It will be implemented in a function which can be called from the main part of the program, and it too will take a flag as parameter to specify which version of the comparison function to call. Of course it will do this by just passing the flag straight through to the comparison function when it is called.

The only other parameters to our bubble sort function will be the array of pointers to the logType structures containing all the data to be sorted and an integer telling the function how many entries there are in the array. Recall that the data itself will stay precisely where it is in memory and only the pointers to the individual pieces of data will be manipulated, within the array, by the bubble sort algorithm.

To implement the algorithm, all we need to do is set up two for loops, one set inside the other. The outer for loop will loop through the entire array n-1 times, whilst the inner one will step through each of the n-1 pairs of adjacent entries in the array so that they can be compared and swapped as necessary.

There is nothing more to a bubble sort algorithm, so we simply implement it now, as follows-na:

void bubbleSort(logType *  * array, int length, int flag)
{
    logType * tempPointer;
	
    for (int i = 0; i < length-1; i++)
        for (int j = 0; j < length-1; j++)
        {
            if (compare(array[j],array[j+1],flag)>0)
            {
                tempPointer = array[j];
                array[j] = array[j+1];
                array[j+1] = tempPointer;
            }
        }
	
    return;
}

Note that we made use of a temporary pointer to store the pointer to the first array entry being swapped whilst it was overwritten with the second array entry. Then the second array entry could be overwritten with the pointer stored in the temporary variable, completing the swap of the two pointers. This method of swapping data is quite common.

Believe it or not, our data is now sorted in memory, and it is time to display the output to the user.