首页 > 解决方案 > 这是进行冒泡排序的正确方法吗?

问题描述

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

    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 < n; i++), 比如for(int j=0; j < 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]+",");


     }

 }
}

标签: javaarrayssortingbubble-sort

解决方案


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

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

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


推荐阅读