冒泡排序为什么叫冒泡排序?

Why bubble sort is called bubble sort?

我正在学习冒泡排序。而且我每次都倾向于忘记排序的类型。所以我试图找到每种排序的逻辑含义,以便它有助​​于回忆排序的逻辑:

我无法理解为什么冒泡排序被命名为冒泡排序的确切含义?

之所以称为冒泡排序,是因为在算法的一次迭代中,smallest/largest 元素将在数组的 end/beginning 的最终位置出现。

所以在某种意义上,在冒泡排序算法的一次迭代中,数组中元素的移动类似于气泡在水中升起的移动

Why is it called bubble sort?

The bubble sort gets its name because elements tend to move up into the correct order like bubbles rising to the surface.

引用自Wikipedia

Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm, which is a comparison sort, is named for the way smaller elements "bubble" to the top of the list.

正如其他答案已经指出的那样,“冒泡排序”之所以这样命名,是因为元素会慢慢移动到列表的所需末端,类似于气泡向表面移动的方式。

因为对于每次迭代,一个元素通过比较和交换冒泡到未排序子序列的最后一个

auto bubble_sort(vector<int>& vs)
{
  int n = vs.size();
  bool swapped = false;
  for(int i = 0; i < n-1; ++i)     // total # of iterations
  {
    for(int j = 0; j < n-i-1; ++j) // each iterations bubbles up 1 element
    {
      if(vs[j] > vs[j+1])
      {
        swap(vs[j], vs[j+1]);
        swapped = true;
      }
    }
    if(!swapped) break;
  }
  return vs;
}