冒泡排序中的比较次数

时间:2018-04-28 02:49:44

标签: 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])) //Swaps the elements
   {
     int temp = array[i]; 
     array[i] = array[i + 1];
     array[i + 1] = temp;
   }
 } 
}
System.out.print("\n\nComparisons:" + count);
}

3 个答案:

答案 0 :(得分:0)

外循环索引 i 与内循环中 j 的所有值相同。看起来比较逻辑应该使用内部循环索引 j

如果count应该记录排序期间完成的交换次数,则可能需要在执行交换的代码块中。目前,count ++将始终执行相同的次数。

答案 1 :(得分:0)

未使用内循环索引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);
}

答案 2 :(得分:0)

试试这个:

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);
}

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

相关问题