Java 冒泡排序中的比较数

Java 冒泡排序中的比较数,java,comparison,counter,bubble-sort,Java,Comparison,Counter,Bubble Sort,我试图在我的冒泡排序类中创建一个比较方法。但是,我一直得到相同的值。有办法解决这个问题吗?谢谢 public void comparisons(int[] array) { int count = 0; for (int i = 0; i < array.length - 1; i++) { for (int j = 0; j < array.length - i - 1; j++) { count++; if ((array[i] > array[i + 1]

我试图在我的冒泡排序类中创建一个比较方法。但是,我一直得到相同的值。有办法解决这个问题吗?谢谢

public void comparisons(int[] array)
{
int count = 0;
for (int i = 0; i < array.length - 1; i++)
{
 for (int j = 0; j < array.length - i - 1; j++)
 {
   count++;
   if ((array[i] > array[i + 1])) //Swaps the elements
   {
     int temp = array[i]; 
     array[i] = array[i + 1];
     array[i + 1] = temp;
   }
 } 
}
System.out.print("\n\nComparisons:" + count);
}
public void比较(int[]数组)
{
整数计数=0;
for(int i=0;i数组[i+1])//交换元素
{
int temp=数组[i];
数组[i]=数组[i+1];
阵列[i+1]=温度;
}
} 
}
系统输出打印(“\n\n比较:“+count”);
}
外循环索引i与内循环中j的所有值相同。看起来比较逻辑应该使用内部循环索引j


如果count应该记录排序期间完成的交换数量,那么它可能需要位于执行交换的代码块中。此时,count++将始终执行相同的次数。

未使用内部循环索引
j
,并且其边界不正确

public void comparisons(int[] array)
{
int count = 0;
for (int i = 0; i < array.length - 1; i++)
{
 for (int j = i; j < array.length - 1; j++)
 {
   count++;
   if ((array[j] > array[j + 1])) //Swaps the elements
   {
     int temp = array[j]; 
     array[j] = array[j + 1];
     array[j + 1] = temp;
   }
 } 
}
System.out.print("\n\nComparisons:" + count);
}
public void比较(int[]数组)
{
整数计数=0;
for(int i=0;iarray[j+1])//交换元素
{
int temp=数组[j];
数组[j]=数组[j+1];
阵列[j+1]=温度;
}
} 
}
系统输出打印(“\n\n比较:“+count”);
}

试试这个:

public void comparisons(int[] array)
{
int count = 0;
for (int i = 0; i < array.length - 1; i++)
{
 for (int j = 0; j < array.length - i - 1; j++)
 {
   if ((array[i] > array[i + 1])) //Swaps the elements
   {
     int temp = array[i]; 
     array[i] = array[i + 1];
     array[i + 1] = temp;
     count++;
   }
 } 
}
System.out.print("\n\nComparisons:" + count);
}
public void比较(int[]数组)
{
整数计数=0;
for(int i=0;i数组[i+1])//交换元素
{
int temp=数组[i];
数组[i]=数组[i+1];
阵列[i+1]=温度;
计数++;
}
} 
}
系统输出打印(“\n\n比较:“+count”);
}

您最好尝试在if条件内增加count的值。根据需要,您可以将
count++
放置在if条件中的任何位置。

根据您的代码,比较的次数始终为
n*(n+1)/2
其中
n=array.length-1
。每次对相同大小的数组进行排序时,它仍然打印相同的数字?比较次数完全由
array.length
array.length
单独决定。也许你想计算互换的数量?我做了更改,但它仍然打印相同的值