【问题标题】:Number of Comparisons in Bubble Sort冒泡排序中的比较次数
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 每次仍然打印相同的数字
  • 您是否总是对相同大小的数组进行排序? 比较次数array.length精确确定,并且仅由array.length 确定。或许您想改为计算 交换次数 的次数?
【解决方案2】:

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

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

【讨论】:

  • 我进行了更改,但仍然打印相同的值
【解决方案3】:

试试这个:

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 条件中的任何位置。

【讨论】:

    猜你喜欢
    • 2016-02-06
    • 2023-03-20
    • 1970-01-01
    • 2018-10-01
    • 2018-05-10
    • 1970-01-01
    • 2018-03-28
    • 1970-01-01
    • 2016-08-11
    相关资源
    最近更新 更多