【问题标题】:I want to understand BubbleSort but I am struggling to understand a specific part in the code my professor provided我想了解 BubbleSort,但我很难理解教授提供的代码中的特定部分
【发布时间】:2021-11-26 02:55:53
【问题描述】:

我不完全理解的唯一部分是内部 for 循环条件。在外部 for 循环中,我们声明 lastPos 是 array.length-1 ,所以如果我们要传递一个大小为 10 的数组,那么 lasPos 将等于 9 对吗?好的,现在在内部 for 循环中,我们说只要 index

//The IntBubbleSorter class provides a public static
//method for performing a bubble sort on an int array
public class IntBubbleSort 
{

    
    public static void main(String[] args)
    {
        int lastPosition;
        int[] myArray = new int[10];
        
        lastPosition = myArray.length-1;
        
        System.out.println(lastPosition);
        
    }
    
    //The bubbleSort method uses the bubble sort algorithm
    //to sort an int array
    
    public static void bubbleSort(int[] array)
    {
        int lastPos;        //Position of the last element to compare
        int i;              //index of an element to compare
        int temp;           //used to swap to elements
        
        //The outer loop positions lastPos at the last element
        //to compare during each pass through the array. Initially
        //lastPos is the index of the last element in the array.
        //During each iteration, it is decreased by one.
        
        for(lastPos = array.length - 1; lastPos >=0 ; lastPos--)
        {
            //The inner loop steps through the array, comparing
            //each element with its neighbor. All of the elements
            //from index 0 through lastPos are involved in the 
            //comparison. If two elements are out of order, they
            //are swapped
            
            for(i = 0; i <= lastPos -1; i++)         //what the hell? 
            {
                //compare an element with its neighbor
                if(array[i] > array[i -1])
                {
                    //swap the two elements
                    temp = array[i];
                    array[i] = array[i+1];
                    array[i +1] = temp;
                }
            }
            
        }
        
    }
    

}

【问题讨论】:

  • 用 3 或 4 个元素的数组在纸上手动写下算法。如果你发现这种方法有问题,或者有改进的余地,那么你可以把它带给你的教授并讨论它。提供的代码也可能是错误的
  • for(i = 0; i &lt;= lastPos -1; i++) 可以重写为for(i = 0; i &lt; lastPos; i++),这是使用从零开始的数组索引的类 c 语言中普遍存在的模因

标签: java arrays algorithm for-loop bubble-sort


【解决方案1】:

首先,代码中有一个错误。这一行:

if(array[i] > array[i -1])

应该是:

if(array[i] > array[i + 1])

这也说明了为什么要循环到lastPos-1:这是因为您将访问一个索引为进一步的数组元素。或者换一种说法:索引 0 和索引 lastPos(包括)之间的子数组中最右边的对,从 lastPos-1 开始。

在您的示例中,我们确实会运行到索引 8。这是因为要比较的最后一对值在索引 8 和 9 处。如果我们会去 9,那么我们会将 9 处的值与 9 处的值进行比较索引 10,但索引 10 将是超出范围的索引。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    相关资源
    最近更新 更多