【问题标题】:Is this the correct way of doing bubble sort?这是进行冒泡排序的正确方法吗?
【发布时间】:2018-06-13 12:43:19
【问题描述】:

只是想知道这是否是进行冒泡排序算法的正确方法。我在互联网上找到了这种做冒泡排序的方式,但我没有得到这个算法的逻辑,这是来自网站的算法:

    int n = arr.length;  
    int temp = 0;  
     for(int i=0; i < n; i++)
           {  
             for(int j=1; j < (n-i); j++)
                 {  
                      if(arr[j-1] > arr[j])
                        {  
                             //swap elements  
                             temp = arr[j-1];  
                             arr[j-1] = arr[j];  
                             arr[j] = temp;  
                        }  

             }  

我知道您需要在 Bubblesort 中使用嵌套循环,但是我不明白的部分是您需要的原因

for(int j=1; j < (n-i); j++){  
    if(arr[j-1] > arr[j]) 

为什么需要“n 减 1”或“j 减 1”,难道你不能只有两个精确的 for 循环,比如 for(int i=0; i &lt; n; i++)for(int j=0; j &lt; n; j++) 作为嵌套循环?谁能给我一个直观的外行术语解释为什么会这样。

因此,我生成了一个带有两个完全相同的嵌套循环的冒泡排序算法。 但是不知道行不行。代码如下:

   import java.lang.Math; // headers MUST be above the first class
   import java.util.Arrays;

   // one class needs to have a main() method
   public class HelloWorld
   {
     // arguments are passed using the text field below this editor
     public static void main(String[] args)
     {


         int integerArray [] = {4,6,1,3,2,8,678,122,12,29,57, -1};
     int temporaryValue;


     for (int i = 0; i < 11; i++)  // integerArray.lenght
     {
       for(int j = 0; j<11; j++)
       {
         if (integerArray [j] > integerArray [j+1])
             {temporaryValue = integerArray[j];
              integerArray [j] = integerArray [j+1];
              integerArray [j+1] = temporaryValue;
             }
       }
     }



   for (int j = 0; j < integerArray.length; j++)
     {
       System.out.print(integerArray[j]+",");


     }

 }
}

【问题讨论】:

  • 冒泡排序保证将一项放置在结构的末尾,因此您无需重新检查它。
  • 如果您找到该代码的网站没有解释它是如何工作的,或者它为什么这样做,那么我建议您不要使用该代码。找一本解释得更详细的书或教程,并尝试自己实现它,而不是仅仅复制你不懂的别人的代码。
  • 致“某程序员老兄”,是的,我就是这么做的,代码基本上是我自己实现的,这是第二部分

标签: java arrays sorting bubble-sort


【解决方案1】:

你需要 (n -i) 因为在每次遍历之后,你知道最大的元素在它的正确位置[end]。所以,你不需要对这个最大的元素执行任何交换操作。它只是减少了交换操作的数量。

你不需要 (j -1)。该示例将 j 从索引 1 迭代到 (n - i)[excluded] 并且您将 j 从索引 0 迭代到 (integerArray.length - 1)[excluded]

建议:拿笔和纸执行你的算法。您将能够理解我们为什么需要 (n -i)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-02
    • 2020-11-20
    • 2020-05-24
    • 1970-01-01
    • 2017-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多