I wrote this code for a bubble sort:
void bubbleSort(int[] a, int first, int last)
{
for (int index = first; index <= last - 1; index++)
for (int element = first; element < last - index; element++)
{
if (comp(a[element], a[element + 1]) > 0)
swap(a, element + 1, element);
}
}
I want to skip unnecessary passes and have the method do less work by remembering where the last swap occurred and only check up to this position on the next pass through the array. When no swaps occur during the last pass, the index of the last swap for this pass would be zero indicating that no further passes are necessary. Any ideas how to implement this?