托人办事送什么礼物较好| 1965年属什么生肖| 血小板偏低有什么危害| 戾什么意思| 六月初三是什么日子| 口角炎用什么药膏| 手指月牙白代表什么| 吃什么可以养肝| 擦汗的表情是什么意思| 形态什么| 羊和什么属相最配| 排便困难拉不出来是什么原因| 什么是蒙氏教育| 门前栽什么树最好| 为什么身体没力气也没有精神| 凝血四项是查什么的| 风言风语是什么意思| 有心火是什么症状| eb病毒是什么病| 乔迁送什么礼物好| 耵聍是什么东西| 肺部占位性的病变指什么| 信任是什么意思| 过期的维生素e有什么用途| 丝瓜不能和什么食物一起吃| 黄精有什么作用| 阳历八月份是什么星座| 台湾为什么叫4v| 痛风吃什么药效果最好| 重庆的市花是什么| 古代地龙是什么| 吃什么卵泡长得快又好| 孕期便秘吃什么通便快| 梦见别人开车撞死人是什么意思| 213是什么意思| 相濡以沫不如相忘于江湖是什么意思| 胃痛按什么部位可以缓解疼痛| 宫颈病变是什么原因引起的| ST是什么| 肌红蛋白高是什么原因| 看脑血管挂什么科| 蒸馏水是什么水| 吃月饼是什么节日| 做胃镜前要注意什么| 妒忌什么意思| 伤风败俗是什么意思| 奴仆宫是什么意思| 汗毛重的女人意味着什么| 喝红茶有什么好处和坏处| 长期失眠应该吃什么药| 猫咪拉肚子吃什么药| 比基尼是什么| 血肌酐低是什么原因| 瘙痒是什么意思| 甲鱼是什么| 属狗的是什么命| 肠胃不好能吃什么水果| 尽性是什么意思| 痔疮是什么东西| np文是什么意思| 大便排不出来是什么原因| 什么水不能喝| 企鹅代表什么生肖| 猫咪能吃什么水果| 有口臭是什么原因引起的| 寻常疣用什么药膏除根| 什么是脚气| 血糖高吃什么肉最好| 日斤念什么字| 县级干部是什么级别| 开心果为什么叫开心果| 卵巢增大是什么原因引起的| 以讹传讹什么意思| 多种维生素什么时候吃效果最好| 麻雀长什么样| 副处级干部是什么级别| 21金维他有什么作用| 维生素b12片治什么病| 希腊脚是什么意思| 峻字五行属什么| 一味是什么意思| 做tct检查前要注意什么| 痛风买什么药| 东北方向五行属什么| 处女是什么象星座| 六点半是什么时辰| 肉蒲团是什么| 血滴子是什么意思| 嘶哑什么意思| 11月21日什么星座| 肠胃炎可以吃什么食物| 健脾胃吃什么| 老婆妹妹叫什么| 负离子有什么作用| 保护肾吃什么食物好| 酒喝多了喝什么解酒| 药占比什么意思| 三顾茅庐是什么意思| 属龙的本命佛是什么佛| 重庆为什么叫雾都| 羊得布病什么症状| 督导是什么| 了不起是什么意思| 弯弯是什么意思| 回盲肠在什么位置| 心电图窦性心律不齐是什么意思| 黄热病是什么病| 80属什么| 随喜是什么意思| 乌合之众什么意思| 少量盆腔积液是什么意思| 站桩有什么好处| 饕餮什么意思| 眼皮突然肿了是什么原因| 属猴配什么属相最好| 度化是什么意思| 牛骨煲汤搭配什么最好| 暗网是什么意思| 月经期肚子疼是什么原因| 胎心不稳定是什么原因| 熟的反义词是什么| 上海市长什么级别| 为什么会血脂高| 低压108有什么危险| 唐伯虎属什么生肖| 瘁是什么意思| 上午12点是什么时候| 黑醋是什么醋| 反颌是什么意思| 什么是三有保护动物| ca125是查什么的| 会车什么意思| 眼睛总是流泪是什么原因| 医保什么时候到账| tac是什么| 崩漏是什么意思| 脸部肌肉跳动是什么原因| 最多笔画的汉字是什么| 什么是占有欲| 痔疮用什么药| 火龙果什么时候成熟| 脸浮肿是什么原因引起的| 什么时候用得| 82年属什么的生肖| 清淡饮食吃什么| 男人时间短什么原因| 女人打掉孩子说明什么| 空调睡眠模式什么意思| 绿茶喝多了有什么危害| 什么食物含钾最高| 霉菌有什么症状| 狗血是什么意思| 过敏性结膜炎用什么眼药水| 薄凉是什么意思| 一什么云彩| 貘是什么| 双侧胸膜增厚是什么病| 卤水点豆腐是什么意思| 恒顺众生是什么意思| 蟹爪兰用什么肥料最好| 什么是一二三级医院| 嫡庶是什么意思| 拔指甲挂什么科| 人中起痘痘是什么原因| 什么的草地| 化疗期间吃什么食物好| 红花泡脚有什么好处| 总放屁是什么病的前兆| 心阳不足吃什么中成药| 大便黑绿色是什么原因| 香港迪士尼什么时候开业的| 瓠子和什么相克| 阴虱用什么药可以根除| 婴儿湿疹用什么| 沁什么意思| 阿尔茨海默症是什么症状| 凤毛麟角是什么生肖| 哥哥的老婆叫什么| 过敏期间不能吃什么东西| 宝宝发烧吃什么食物好| 干什么能挣钱快| 附件是什么意思| 身上起红疙瘩是什么原因| 伶字五行属什么| 咳嗽吃什么药效果好| 净身出户需要什么条件| 传单是什么病| 鱼露是什么味道| 吃什么排黑色素最强| 身份证后四位代表什么| 宫外孕和宫内孕有什么区别| 六度万行 是什么意思| 人到无求品自高什么意思| 梦见牙掉了一颗是什么意思| 清秋是什么意思| 什么地方黄鳝最多| 黄茶适合什么人喝| 淋巴细胞比率偏高是什么原因| 女生是t是什么意思| 糖醋排骨用什么醋好吃| 什么烧鸡好吃| 七月初七是什么节日| 半路杀出个程咬金是什么意思| 糖粉和白糖有什么区别| 止疼药吃多了有什么副作用| 肌无力有什么症状| 糖类抗原199偏高是什么原因| 吃山药有什么好处| 金瓜是什么瓜| 什么食物含钾多| 桌游是什么| 属虎和什么属相相冲| 属牛本命佛是什么佛| 省军区司令员是什么级别| 什么水果止咳| 血细胞分析能查出什么| 处女座的幸运数字是什么| 咀嚼什么意思| 殁送是什么意思| 什么叫有机| 绿洲是什么意思| 手足口病忌口什么食物| 月支是什么意思| 拔萝卜什么意思| 吃什么代谢快有助于减肥| 左肾囊性灶是什么意思| 维生素b2起什么作用| 滋阴润燥是什么意思| 生辰八字五行缺什么| 女人喝什么调节内分泌| 胚发育成什么| 玄五行属什么| 拉肚子应该吃什么| 抓手是什么意思| 舌头中间裂纹是什么病| 家里蟑螂多是什么原因| 牵牛花为什么叫牵牛花| 河虾吃什么| 淋巴细胞百分比偏高是什么原因| 拉姆是什么意思| 狼吞虎咽是什么生肖| 为什么牙齿会发黑| 什么是伤官见官| 小李子为什么叫小李子| vivo什么牌子| 产后复查挂什么科| md是什么意思| 宫颈液基细胞学检查是什么| 岗位等级是什么意思| 中医为什么下午不把脉| 阳虚是什么原因引起的| rush是什么意思| 金目念什么| 性交是什么| 见红的血是什么颜色| 羹什么意思| 甘草泡水喝有什么好处和坏处| 肚脐下方硬硬的是什么| 冲奶粉用什么水比较好| 乔迁对联什么时候贴| 4月1日是什么星座| 营长是什么军衔| 左肾钙乳症是什么病| 为什么脚会肿起来是什么原因| 百度Jump to content

a href=httpwww.chinanews.comgj201803-258475458.shtml target=

From Wikipedia, the free encyclopedia
Content deleted Content added
Lp.vitor (talk | contribs)
Undid revision 908491336 by Glrx (talk) - CLRS is one of the most widely used books to teach Algorithm. That version of bubblesort exists and must be documented.
Lp.vitor (talk | contribs)
Variations: Adding more information about the quadratic time complexity in best-case.
Line 144: Line 144:


== Variations ==
== Variations ==
* Some authors call Bubble sort the version with the swap test (that has linear time best-case complexity), while for others, Bubble sort is the most simple version whose time complexity is always quadratic.
* [[Odd–even sort]] is a parallel version of bubble sort, for message passing systems.
* [[Odd–even sort]] is a parallel version of bubble sort, for message passing systems.
* Passes can be from right to left, rather than left to right. This is more efficient for lists with unsorted items added to the end.
* Passes can be from right to left, rather than left to right. This is more efficient for lists with unsorted items added to the end.

Revision as of 12:21, 3 September 2019

Bubble sort
Static visualization of bubble sort[1]
ClassSorting algorithm
Data structureArray
Worst-case performance comparisons, swaps
Best-case performance comparisons for basic version and for the optimized one, swaps
Average performance comparisons, swaps
Worst-case space complexity auxiliary
OptimalNo
百度 “我的其中一位最好的朋友在这里被枪杀,所以(这次的游行)对我很重要。

Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. The algorithm, which is a comparison sort, is named for the way smaller or larger elements "bubble" to the top of the list. Although the algorithm is simple, it is too slow and impractical for most problems even when compared to insertion sort.[2] Bubble sort can be practical if the input is in mostly sorted order with some out-of-order elements nearly in position.

Analysis

An example of bubble sort. Starting from the beginning of the list, compare every adjacent pair, swap their position if they are not in the right order (the latter one is smaller than the former one). After each iteration, one less element (the last one) is needed to be compared until there are no more elements left to be compared.

Performance

Bubble sort has a worst-case and average complexity of О(n2), where n is the number of items being sorted. Most practical sorting algorithms have substantially better worst-case or average complexity, often O(n log n). Even other О(n2) sorting algorithms, such as insertion sort, generally run faster than bubble sort, and are no more complex. Therefore, bubble sort is not a practical sorting algorithm.

The only significant advantage that bubble sort has over most other algorithms, even quicksort, but not insertion sort, is that the ability to detect that the list is sorted efficiently is built into the algorithm. When the list is already sorted (best-case), the complexity of bubble sort with a swap-checking variable is only O(n) (although the most basic implementation is O(n2) even in the best-case[3]). By contrast, most other algorithms, even those with better average-case complexity, perform their entire sorting process on the set and thus are more complex. However, not only does insertion sort share this advantage, but it also performs better on a list that is substantially sorted (having a small number of inversions).

Bubble sort should be avoided in the case of large collections. It will not be efficient in the case of a reverse-ordered collection.

Rabbits and turtles

The distance and direction that elements must move during the sort determine bubble sort's performance because elements move in different directions at different speeds. An element that must move toward the end of the list can move quickly because it can take part in successive swaps. For example, the largest element in the list will win every swap, so it moves to its sorted position on the first pass even if it starts near the beginning. On the other hand, an element that must move toward the beginning of the list cannot move faster than one step per pass, so elements move toward the beginning very slowly. If the smallest element is at the end of the list, it will take n?1 passes to move it to the beginning. This has led to these types of elements being named rabbits and turtles, respectively, after the characters in Aesop's fable of The Tortoise and the Hare.

Various efforts have been made to eliminate turtles to improve upon the speed of bubble sort. Cocktail sort is a bi-directional bubble sort that goes from beginning to end, and then reverses itself, going end to beginning. It can move turtles fairly well, but it retains O(n2) worst-case complexity. Comb sort compares elements separated by large gaps, and can move turtles extremely quickly before proceeding to smaller and smaller gaps to smooth out the list. Its average speed is comparable to faster algorithms like quicksort.

Step-by-step example

Take an array of numbers " 5 1 4 2 8", and sort the array from lowest number to greatest number using bubble sort. In each step, elements written in bold are being compared. Three passes will be required;

First Pass
( 5 1 4 2 8 ) → ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) → ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) → ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) → ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass
( 1 4 2 5 8 ) → ( 1 4 2 5 8 )
( 1 4 2 5 8 ) → ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) → ( 1 2 4 5 8 )
( 1 2 4 5 8 ) → ( 1 2 4 5 8 )

Now, the array is already sorted, but the algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.

Third Pass
( 1 2 4 5 8 ) → ( 1 2 4 5 8 )
( 1 2 4 5 8 ) → ( 1 2 4 5 8 )
( 1 2 4 5 8 ) → ( 1 2 4 5 8 )
( 1 2 4 5 8 ) → ( 1 2 4 5 8 )

Implementation

Pseudocode implementation

In pseudocode, the basic algorithm can be expressed as follows (using 0-based arrays)[3]:

procedure bubbleSort(A : list of sortable items )
    n = length(A)
    for i = 1 to n-1 inclusive do
       for j = n-1 downto i inclusive do
            /* if this pair is out of order */
            if A[j-1] > A[j] then
                /* swap them */
                swap( A[j-1], A[j] )
            end if
        end for
    end for
end procedure

A little modification can be done to improve the best-case time complexity from to , that is, one can create a variable to check if some swap was performed in the current step:[4]

procedure bubbleSort(A : list of sortable items )
    n = length(A)
    repeat
        swapped = false
        for i = 1 to n-1 inclusive do
            /* if this pair is out of order */
            if A[i-1] > A[i] then
                /* swap them and remember something changed */
                swap( A[i-1], A[i] )
                swapped = true
            end if
        end for
    until not swapped
end procedure

Optimizing bubble sort

The bubble sort algorithm can be easily optimized by observing that the n-th pass finds the n-th largest element and puts it into its final place. So, the inner loop can avoid looking at the last n ? 1 items when running for the n-th time:

procedure bubbleSort( A : list of sortable items )
    n = length(A)
    repeat
        swapped = false
        for i = 1 to n-1 inclusive do
            if A[i-1] > A[i] then
                swap(A[i-1], A[i])
                swapped = true
            end if
        end for
        n = n - 1
    until not swapped
end procedure

More generally, it can happen that more than one element is placed in their final position on a single pass. In particular, after every pass, all elements after the last swap are sorted, and do not need to be checked again. This allows to skip over many elements, resulting in about a worst case 50% improvement in comparison count (though no improvement in swap counts), and adds very little complexity because the new code subsumes the "swapped" variable:

To accomplish this in pseudocode, the following can be written:

procedure bubbleSort( A : list of sortable items )
    n = length(A)
    repeat
        newn = 0
        for i = 1 to n-1 inclusive do
            if A[i-1] > A[i] then
                swap(A[i-1], A[i])
                newn = i
            end if
        end for
        n = newn
    until n <= 1
end procedure

Alternate modifications, such as the cocktail shaker sort attempt to improve on the bubble sort performance while keeping the same idea of repeatedly comparing and swapping adjacent items.

Use

A bubble sort, a sorting algorithm that continuously steps through a list, swapping items until they appear in the correct order. The list was plotted in a Cartesian coordinate system, with each point (x, y) indicating that the value y is stored at index x. Then the list would be sorted by bubble sort according to every pixel's value. Note that the largest end gets sorted first, with smaller elements taking longer to move to their correct positions.

Although bubble sort is one of the simplest sorting algorithms to understand and implement, its O(n2) complexity means that its efficiency decreases dramatically on lists of more than a small number of elements. Even among simple O(n2) sorting algorithms, algorithms like insertion sort are usually considerably more efficient.

Due to its simplicity, bubble sort is often used to introduce the concept of an algorithm, or a sorting algorithm, to introductory computer science students. However, some researchers such as Owen Astrachan have gone to great lengths to disparage bubble sort and its continued popularity in computer science education, recommending that it no longer even be taught.[5]

The Jargon File, which famously calls bogosort "the archetypical [sic] perversely awful algorithm", also calls bubble sort "the generic bad algorithm".[6] Donald Knuth, in 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", some of which he then discusses.[2]

Bubble sort is asymptotically equivalent in running time to insertion sort in the worst case, but the two algorithms differ greatly in the number of swaps necessary. Experimental results such as those of Astrachan have also shown that insertion sort performs considerably better even on random lists. For these reasons many modern algorithm textbooks avoid using the bubble sort algorithm in favor of insertion sort.

Bubble sort also interacts poorly with modern CPU hardware. It produces at least twice as many writes as insertion sort, twice as many cache misses, and asymptotically more branch mispredictions.[citation needed] Experiments by Astrachan sorting strings in Java show bubble sort to be roughly one-fifth as fast as an insertion sort and 70% as fast as a selection sort.[5]

In computer graphics bubble sort is popular for its capability to detect a very small error (like swap of just two elements) in almost-sorted arrays and fix it with just linear complexity (2n). For example, it is used in a polygon filling algorithm, where bounding lines are sorted by their x coordinate at a specific scan line (a line parallel to the x axis) and with incrementing y their order changes (two elements are swapped) only at intersections of two lines. Bubble sort is a stable sort algorithm, like insertion sort.

Variations

  • Some authors call Bubble sort the version with the swap test (that has linear time best-case complexity), while for others, Bubble sort is the most simple version whose time complexity is always quadratic.
  • Odd–even sort is a parallel version of bubble sort, for message passing systems.
  • Passes can be from right to left, rather than left to right. This is more efficient for lists with unsorted items added to the end.
  • Cocktail shaker sort alternates leftwards and rightwards passes.

Debate over name

Bubble sort has been occasionally referred to as a "sinking sort".[7]

For example, in Donald Knuth's The Art of Computer Programming, Volume 3: Sorting and Searching he states in section 5.2.1 'Sorting by Insertion', that [the value] "settles to its proper level" and that this method of sorting has sometimes been called the sifting or sinking technique.[clarification needed]

This debate is perpetuated by the ease with which one may consider this algorithm from two different but equally valid perspectives:

  1. The larger values might be regarded as heavier and therefore be seen to progressively sink to the bottom of the list
  2. The smaller values might be regarded as lighter and therefore be seen to progressively bubble up to the top of the list.

Notes

  1. ^ Cortesi, Aldo (27 April 2007). "Visualising Sorting Algorithms". Retrieved 16 March 2017.
  2. ^ a b Donald Knuth. The Art of Computer Programming, Volume 3: Sorting and Searching, Second Edition. Addison-Wesley, 1998. ISBN 0-201-89685-0. Pages 106–110 of section 5.2.2: Sorting by Exchanging. "[A]lthough the techniques used in the calculations [to analyze the bubble sort] are instructive, the results are disappointing since they tell us that the bubble sort isn't really very good at all. Compared to straight insertion […], bubble sorting requires a more complicated program and takes about twice as long!" (Quote from the first edition, 1973.)
  3. ^ a b Cormen, Thomas H.; Leiserson, Charles E.; Rivest, Ronald L.; Stein, Clifford (2001). Introduction to Algorithms (2nd ed.). Problem 2-2: MIT Press and McGraw-Hill. p. 40. ISBN 0-262-03293-7.{{cite book}}: CS1 maint: location (link)
  4. ^ Knuth, Donald E. (1998). The Art of Computer Programming: Volume 3 (2nd ed.). Chapter 5, Section 5.2.2: Addison-Wesley Professional. p. 107. ISBN 978-0201896855.{{cite book}}: CS1 maint: location (link)
  5. ^ a b Astrachan, Owen (2003). "Bubble sort: an archaeological algorithmic analysis" (PDF). ACM SIGCSE Bulletin. 35 (1): 1–5. doi:10.1145/792548.611918. ISSN 0097-8418.
  6. ^ "jargon, node: bogo-sort".
  7. ^ Black, Paul E. (24 August 2009). "bubble sort". Dictionary of Algorithms and Data Structures. National Institute of Standards and Technology. Retrieved 1 October 2014.

References

打呼噜什么原因 新生儿便秘吃什么好 你本来就很美是什么广告 什么时候闰十二月 树大招风的意思是什么
93鸡和94狗生什么宝宝 夜晚咳嗽是什么原因 乳腺结节是什么原因引起的 6.1什么星座 子宫前位后位有什么区别
着凉了吃什么药 浸润癌是什么意思 七八年属什么生肖 苍龙七宿的秘密是什么 观赏是什么意思
鸳鸯是什么意思 荷花什么时候种植 女性检查生育挂什么科 长裙配什么鞋 鳌是什么意思
抽搐是什么意思hcv8jop3ns2r.cn 湿热带下是什么意思hcv8jop2ns1r.cn 头部挂什么科hkuteam.com 动漫是什么意思hcv9jop7ns1r.cn 12月14号是什么星座mmeoe.com
抗炎是什么意思hcv9jop1ns8r.cn 指甲长得快是什么原因jinxinzhichuang.com 肝钙化灶是什么意思baiqunet.com 北漂是什么意思hcv9jop4ns3r.cn 晚上睡觉磨牙是什么原因hcv8jop8ns1r.cn
多多益善的意思是什么hcv9jop6ns1r.cn 疏导是什么意思hcv8jop9ns1r.cn 甲泼尼龙主要治什么hcv8jop9ns0r.cn 猴子下山的故事告诉我们什么hcv8jop2ns1r.cn 吃虾不能和什么一起吃qingzhougame.com
百香果和什么搭配好喝hcv9jop1ns8r.cn 马上好药膏主治什么hcv8jop2ns7r.cn 孕晚期吃什么水果好hcv8jop9ns4r.cn 3月16日是什么星座1949doufunao.com 胃酸想吐是什么原因hcv9jop5ns4r.cn
百度