The pset 3 short on bubble sorting mentions that we should:
1) set a swap counter to a non-zero value.
2) Define the loop
3) In each loop iteration reset the counter to 0 and increase the swap counter if a swap of two array elements occurs.
4) after the loop if the swap counter is 0, terminate the sort
I understand the reason for this which is to stop the recursive bubble sort early if the data is sorted rather than running through up to n^2 loops.
However in my code I declare my swap counter and define it to be 0 rather than a non-zero value and it still seems to work. I don't find I need a non-negative value:
void sort(int array[], int size)
{
if (size <= 1)
return;
int swapCounter = 0;
for(int j = 0; j < size - 1; j++)
{
if (array[j] > array[j + 1])
{
int swap = array[j + 1];
array[j + 1] = array[j];
array[j] = swap;
swapCounter++;
}
}
if (swapCounter > 0)
sort(array, size - 1);
}
Is there something I am missing?
Do I need to set swapCounter to a non-zero integer before I define my for loop?
Or is this only neccessary when using do...while loops?