I am having trouble understanding how comparisons work and how many are made in bubble sort(or any sort for that matter). In my example code for bubble sort:
public class BS
{
public static void main (String[] args)
{
int[] Array = {5,1,4,2,8};
System.out.println("Array Before Bubble Sort:");
for (int element : Array)
System.out.print(element + " ");
bubbleSort(Array);
System.out.println("Array After Bubble Sort:");
for (int element : Array)
System.out.print(element + " ");
System.out.print("\n");
}
public static void bubbleSort(int[] array)
{
int lastPos;
int index;
int temp;
int comp = 0;
int swap = 0;
for(lastPos = array.length - 1; lastPos >= 0; lastPos--)
{
for(index = 0; index <= lastPos - 1; index++)
{
comp++;
if(array[index] > array[index + 1])
{
swap++;
temp = array[index];
array[index] = array[index + 1];
array[index + 1] = temp;
}
}
}
System.out.println("\nComparisons: " + comp);
System.out.println("Swaps: " +swap;
}
}
The output is this:
Array Before Bubble Sort:
5 1 4 2 8
Comparisons: 10
Swaps: 4
Array After Bubble Sort:
1 2 4 5 8
As far as I can tell, the number of swaps is correct but shouldn't the number of comparisons be 12? No matter what numbers I put in the array, the number of comparisons is always 10. Aren't bubble sort comparisons different for different arrays? Or it depends on the size of the array? I couldn't find any insight on this and I'm genuinely confused. I'd appreciate some help and I will edit with more information if needed.
Without a check to see if your array is sorted, it will always perform a constant number of checks based on the size of the array.
In your for loops, if you have a check to see if you did an entire pass without any swaps, then you can exit early which would mean that sorting an already sorted array containing 5 elements would only take 4 comparisons.
When testing your algorithms you should always throw edge cases at them, for instance what is the outcome of your algorithm on
{}
{1}
{0,0,0,0}
{1,1,3,1,1}
{1,2,3,4,5,6}
{10,9,8,7,6,5,4,3,2,1,}
{1,5,1,5,1,5,1,5,1,5,1}
As well as a few genuinely random sequences.