问题
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.
回答1:
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.
回答2:
The best case, worst case, average case for Bubble Sort is always the same, no matter what values are in the array. It will always compare each value with each of the following values even if the array is already properly sorted. So you are correct when you say that the comparisons will only change based on the number of values in the array
回答3:
Bubble sort comparison depends only on number of elements in list. Firstly it will do 4 comparisons, then 3, then 2 and lastly 1 for your given example with 5 elements. It won't swap them if they are in their righteous place.
来源:https://stackoverflow.com/questions/46773166/bubble-sort-comparison-count-is-always-the-same