【发布时间】:2018-04-28 02:49:43
【问题描述】:
我正在尝试在我的冒泡排序类中创建一种比较方法。但是,我一直得到相同的值。有没有什么办法解决这一问题?谢谢。
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);
}
【问题讨论】:
-
比较次数,根据您的代码,始终为
n*(n+1)/2,其中n = array.length - 1。
标签: java comparison counter bubble-sort