简体   繁体   English

如何理解这种冒泡数组排序

[英]How to understand this bubble array sort

How did it working when both the loop is starting from 0 and comparison between both indexes have the same value当两个循环都从 0 开始并且两个索引之间的比较具有相同的值时它是如何工作的

public class BubbleSort {
    public static void main(String[] args)
    {
        int arr[]={5,1,2,1,1,4,4,4,4,4,3};

        for(int i=0;i<arr.length;i++)//i=0
        {
            for(int j=0;j<arr.length;j++)//j=0
            {
                if(arr[i]>arr[j])//i=5>j=5
                {
                   int temp=arr[i];
                   arr[i]=arr[j];
                   arr[j]=temp;
                }
            }
        }
        for(int k=0;k<arr.length;k++)
            System.out.println(arr[k]);
        }
    }
}

So, if I try to summarize your code:因此,如果我尝试总结您的代码:

  1. There are two loops (with iterators i and j)有两个循环(带有迭代器 i 和 j)

  2. In the first for loop, we take each element of the array one by one and then we compare that element (lets call it 'current element') with other elements (including the 'current element', because it is possible that i and j have same values ie i=0, j=0; i=1, j=1) in the second for loop.在第一个 for 循环中,我们一个一个地取数组的每个元素,然后将该元素(我们称之为“当前元素”)与其他元素(包括“当前元素”,因为 i 和 j 可能在第二个 for 循环中具有相同的值,即 i=0, j=0; i=1, j=1)。

  3. Now, in this comparison, if the 'current element' is greater than the elements we are comparing in the second for loop, then we swap the element.现在,在这个比较中,如果“当前元素”大于我们在第二个 for 循环中比较的元素,那么我们交换元素。

  4. So, as the execution continuous, the elements with bigger value will move towards the right side of the array and elements with smaller value will move towards left side of the array.因此,随着执行的不断进行,值较大的元素将向数组的右侧移动,而值较小的元素将向数组的左侧移动。

  5. Eventually the array will be sorted.最终数组将被排序。

Its called bubble sort, because the elements are sorted and move up to the array like bubbles.它被称为冒泡排序,因为元素被排序并像冒泡一样向上移动到数组。

You can find more info here: https://www.hackerearth.com/practice/algorithms/sorting/bubble-sort/tutorial/您可以在此处找到更多信息: https : //www.hackerearth.com/practice/algorithms/sorting/bubble-sort/tutorial/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM