What is a bubble sort good for? [closed]

2019-01-07 08:31发布

Do bubble sorts have any real world use? Every time I see one mentioned, it's always either:

  1. A sorting algorithm to learn with.
  2. An example of a sorting algorithm not to use.

16条回答
再贱就再见
2楼-- · 2019-01-07 08:32

It's good for small data sets - which is why some qsort implementations switch to it when the partition size gets small. But insertion sort is still faster, so there's no good reason to use it except as a teaching aid.

查看更多
Root(大扎)
3楼-- · 2019-01-07 08:34

It depends on the way your data is distributed - if you can make some assumptions.

One of the best links I've found to understand when to use a bubble sort - or some other sort, is this - an animated view on sorting algorithms:

http://www.sorting-algorithms.com/

查看更多
三岁会撩人
4楼-- · 2019-01-07 08:34

Bubble sort is easy to implement and it is fast enough when you have small data sets.

Bubble sort is fast enough when your set is almost sorted (e.g. one or several elements are not in the correct positions), in this case you better to interlace traverses from 0-index to n-index and from n-index to 0-index. Using C++ it can be implemented in the following way:

void bubbleSort(vector<int>& v) { // sort in ascending order
  bool go = true;
  while (go) {
    go = false;
    for (int i = 0; i+1 < v.size(); ++i)
      if (v[i] > v[i+1]) {
         swap(v[i], v[j]);
         go = true;
      }
    for (int i = (int)v.size()-1; i > 0; --i) 
      if (v[i-1] > v[i]) {
         swap(v[i-1], v[i]);
         go = true;
      }
  }
}

It can be good if swap of two adjacent items is chip and swap of arbitrary items is expensive.

Donald Knuth, in his famous "The Art of Computer Programming", concluded that "the bubble sort seems to have nothing to recommend it, except a catchy name and the fact that it leads to some interesting theoretical problems".

Since this algorithm is easy to implement it is easy to support, and it is important in real application life cycle to reduce effort for support.

查看更多
手持菜刀,她持情操
5楼-- · 2019-01-07 08:37

It's quick and easy to code and (nearly impossible to do wrong). It has it's place if you're not doing heavy lifting and there's no library sorting support.

查看更多
在下西门庆
6楼-- · 2019-01-07 08:37

Mostly nothing. Use QuickSort or SelectionSort instead...!

查看更多
三岁会撩人
7楼-- · 2019-01-07 08:37

Oh yes, it is a good selection mechanism. If you find it in code written by someone, you don't hire him.

查看更多
登录 后发表回答