Talk:Bubble sort

message: hey why isn't XOR swapping used in any of the examples?  i replaced the C code but someone will have to do the rest cuz i'm not familiar with them.
::It's clever, but it's also ugly. Even worse, it's an uncommon enough idiom that it's generally more confusing than anything. Flatline 03:52, 2005 Apr 6 (UTC) 
::According to xor swap algorithm, xor swapping is less efficient on modern processors than regular swapping using a temp variable. So, if it's uglier and slower than the normal way, why would you want to encourage its use? Flatline 17:56, 2005 Apr 7 (UTC)
::I disagree that xor swap is ugly.  It's ugly when applied to situations where an ordinary swap works just as well.  xor swap is useful for the special problem of swapping a subset of bit positions between two binary processor registers; it elimates unnecessary masking steps in the use of the temporary register.  When applied in this context, xor bit swap allows one to construct an efficient 8x8 bit transpose using a pair of 32 bit binary registers and plenty of bit rotations.  It doesn't belong here by any means.  The application of boolean valued xor swap to bubble sorting a binary valued sequence is too mirthful to contemplate.  
----
I have removed all the implementations except one; wikipedia guidelines are quite clear that implementations are merely for helping the reader understand the concept better. More than one is definitely a no-no (and so are hacks for improving effiency). Wikicode implementations are preferred; I left the python impl in because I felt it is most similar to wikicode. Anyone who wants to replace it with wikicode is welcome. Arvindn 19:44, 3 Dec 2004 (UTC)
thread_title:  XOR swapping 

message: The implementation has been written in Wikicode. We only need to see it once. All you VB programmers and whatnot can grab your implementations from the page history and contribute them to the linked Wikisource page, which can grow to your heart's delight. There's no reason to have that many implementations when we're just looking to explain the algorithm, not write a treatise on the proper reinvention of the wheel in STL. grendel|khan 21:13, 2005 Mar 18 (UTC)
----
If that implementation is correct Wikicode then Wikicode is quite an unorthodox thing...  As I see it, the swap line should be something like
   swap(A,j,j+1)
The code right now really doesn't look like the function Swap() would swap the contents of the two adjacent indexes in the array.  It looks like a confusion between values and references.
Let me be clear about this:
Function bubblesort is given a list[1..n] of type ElementType.
What function Swap should get is the list plus two positions in the list - those positions that need to be swapped.  Swap would be:
   function swap(A : list[1..n] of ElementType, i:index, j:index) {
      var temp : ElementType;
      temp:=A[i];
      A[i]:=A[j];
      A[j]:=temp;
   }
What about the current function?  How does
   swap(i:ElementType, j:ElementType)
look like?
--Matti 13:33, 30 June 2006 (UTC)
replies: text: Well, I think it's confusing to you primarily because you assign conventional value-passing semantics to it. It's easy to write for example a macro in C or a function in C++ taking reference parameters that would correctly execute this code. In some languages, all parameters are passed by reference by default. Considering that the intent is clear, I don't see a problem. Deco 13:38, 30 June 2006 (UTC)
replies: text: Humm, I got to this page because of curiousity about "Wikicode".  I was looking for examples of wikicode, and found that piece of code to look a bit odd, perhaps because the wikicode syntax resembles Pascal/C and wikicode is argued to be an imperative language (hence my hasty interpretation of value-passing semantics).  Wikicode specs are, of course, merely suggestive, and since wikicode is pseudocode, it doesn't really matter how it's being written as long as the intent is clear.  Although I'd write it differently, I see your point.  There's no need to continue debate.  --Matti 14:53, 30 June 2006 (UTC)
thread_title:  Wikicode used. 

message: Re: the bit in the article "Bubble sort is asymptotically equivalent in running time to insertion sort, but the two algorithms differ greatly in the number of swaps necessary. In the worst case, bubble sort will require O(n2) swaps, while insertion sort will require at most O(n) swaps."... No.
Bubble sort and insertion sort are not "asymptotically equivalent".  On average...
  Bubble sort does a little less than N^2/2 swaps.  Insertion sort does a little over N^2/4 moves (NOT swaps).
  (swaps may take anything from 1x to 3x as long as moves, depending on the CPU architecture).
  Bubble sort does just under N^2/2 comparisons.  Insertion sort does a little over N^2/4.
  If the CPU has a cache, and N is sufficiently large, Bubble Sort requires approximately twice as many cache flushes.
  On pipelined architectures, Bubble Sort results in O(N*log(N)) branch mispredictions
  (that is, the total count of left-to-right minima found during the sort).
  Insertion sort: O(N).
...and so bubble sort's asymptotic running time is - typically - twice that of insertion sort.
When N is small, on a pipelined architecture, it is worse even than that.
--James Barbetti, 10-July-2005
:You are correct, bubble sort is considerably slower in practice for a variety of reasons, but a constant multiple performance difference is still "asymptotically equivalent", by definition. Some of these stats would be great to add to the article in the new performance section. Deco 03:09, 18 November 2005 (UTC)
thread_title:  Bubble Sort is also rather slower than Insertion Sort, on average  

message: Shouldn't the best case be only O(n) as it makes one pass over the elements? The page quotes O(n^2) as the best case running time, this has to be a mistake.
128.175.166.74 21:16, 17 October 2005 (UTC)
thread_title:  Best Case Analysis? 

message: I've added a variety of things to the article that may be considered disparaging of bubble sort. I just wanted to clarify that I have nothing personally against bubble sort and I'm really just trying to add more information to the article. I do not agree with Astrachan's assertion that bubble sort should no longer be taught; I think every sort algorithm has something to add. Deco 03:21, 18 November 2005 (UTC)
thread_title:  Recent disparaging changes 

message: In all my years of coding and applications and simulations I've written, I have come across one instance where bubble sort was the best option.  It was in an application that kept the order of simulated traffic moving from one side to another in a torroid shape where an entity would occasionally wrap around the edge to the other side.  Each entity could only pass at maximum one other entity per turn, but the list order could not be modified until all turns were taken by each entity.  Using bubble sort on this resulted in one pass across the list over 99% of the time (and the < 1% was always less than 2 passes).  Note that this was also a realtime application.  Granted, very few programmers will ever run into a situation remotely like this, but it was one case where bubble sort was the best option.  (Note that I am using the generic words traffic and entity to not give away things covered by an NDA.)
:That is interesting. I see how a few elements wrapping around like that could favour bubble sort, especially the variation with the extra flags. I'm sure an application-specific algorithm could do better, but at least bubble sort is already well-researched. I'm afraid it's obscure enough though that I'd opt to keep it here on the talk page. Deco 00:26, 6 December 2005 (UTC)
replies: text: Another note is that bubble sort lends itself very well to parallelization, especially on SIMD architectures.  Each processor can handle comparing and swapping pairs of elements, then each iteration the pair boundaries shift, resulting in (with N/2 processors) a running time of O(N).  —Preceding unsigned comment added by 204.111.162.215 (talk) 19:18, 31 October 2009 (UTC)
thread_title:  Bubble sort does have exceedingly rare uses 

message: I suggest changing the explanation of it's name to: "The algorithm gets its name from the way smaller or larger elements "bubble" to the top (i.e. head) of the list via the swaps. The bubble sort can be implemented to sort in ascending or descending order."
My thinking is that people are used to counting from smallest number to biggest number and also it is a small sentence that clarifies this sort can be done both ways.  If someone is starting out in programming they might not realize this.  I say for accuracy and understandability the change is implemented and left alone. (anon post)
:I understand why you consider this a useful addition, but I respectfully disagree. Simply changing the comparison from "<" to ">=" in any comparison sort will reverse the sorting order; therefore this statement is not at all specific to bubble sort and better discussed in the more general comparison sort article, as it is. The placement here suggests that this is a special property or advantage of bubble sort. Deco 03:59, 14 December 2005 (UTC)
thread_title: Ascending/Descending

message: I was under the impression that bubble sort would repeatedly go through the entire list until no swaps were required.  The first paragraph of this article describes it this way.  Then, when describing it "in more detail", it uses a slightly different algorithm, where each pass through the list is slightly shorter, and the loop keeps going regardless of whether swaps are required.  It would be nice if this could be clarified.  I checked out Sedgewick (Algorithms, 2nd ed) and he does the same thing; he first describes it as repeatedly passing through the whole file until no swaps are required, and then gives sample code which is equivalent to the sample code from this article.  Strange.  (I don't have Knuth so I can't check to see how he defines it.)  Pfalstad 00:14, 9 January 2006 (UTC)
thread_title:  what is bubble sort? 

message: Rewrote most of the top half.
Pfalstad: It's been clarified, hopefully. See "Alternative implementations".
Jafet 16:16, 12 August 2006 (UTC)
thread_title: Revamp

message: The article is a little inconsistent about the goal of the sort.  Throughout most (maybe all) of the text under headings, we are talking about sorting an array from greatest to least.  But the psuedocode seems to sort an array from least to greatest.  I understand that the bubble sort can be designed to do either, but to avoid confusing the reader, we should pick one and stick with it. --Nave251 21:51, 13 November 2006 (UTC)
thread_title:  Greatest to least or least to greatest? 

message: ::Comb sort compares elements large gaps apart and can move turtles extremely quickly, before proceeding to smaller and smaller gaps to smoothen out the list. Its average speed is comparable to faster algorithms like Quicksort.
Superficially, it is not immediately apparent that it is Comb sort which is comparable to QuickSort, and not BubbleSort (which the article is about). I suggest either removing the comparison or putting it in the preceding sentence to make this clearer. 
BubbleSort itself, of course, has worst and average complexity of O(n^2).
--- Arancaytar - avá artanhé (reply) 20:59, 29 April 2007 (UTC)
thread_title:  ambiguous comparison to QuickSort 

message: A "sample implementations" section has recently been added to the article, with a Java example.  I'm not a sure this is a good idea, for two reasons:
*We already have a perfectly-clear pseudo-code rendition, which should be understandable no matter what real-world language the reader is used to.  If the reader isn't capable of translating that into language X, then they really should spend more time learning the basics of language X.
*In the long run, this kind of section just leads to everyone adding an implementation in their favourite language, which unnecessarily bloats the article.
In short, I'm don't think real-world implementations add anything to the article, and have the tendency to make the article worse.  See also Wikipedia:Articles for deletion/Insertion sort implementations.  Oli Filth(talk) 08:29, 28 November 2007 (UTC)
thread_title:  Sample implementations 

message: I have noticed that this page has 3 versions of this algorithm. One with the most basic type (which always have complexity O(n^2)), one with a revised code that can terminate earlier (which the example is written for), and one with one more improvement (which is filed under "alternative implementations"). Adding the (lowest to greatest)-(greatest to lowest) variability, I think this does nothing but confuse the reader.
Besides, I think that this flow of contents is not "natural". I mean one needs to have some info to be able to understand what a piece of code is about, and an example after seeing the code to understand better.
My suggestion is to reorder the whole article as:
*Firstly, a not-so-detailed explanation, with a consensus on the order of final array (increasing sort or decreasing sort)
*Secondly, pseudocode of the most basic form (I actually don't think this is even needed, but since it is here, maybe we should keep it)
*Thirdly, a not-so-detailed explanation of improvements that can be made
*Then, a pseudocode with all those improvements, not a pseudocode for each improvement as it is the case now (I guess we can make just these two improvements, but who knows?)
*Then, a step-by-step example
*Then, the analysis part with all details that are skipped before
*Then, "In practice", "Variations", "References", etc.
If we all agree on this flow, we should edit the other algorithms as well...
What do you say? --Vdaghan (talk) 17:45, 15 January 2008 (UTC)
thread_title:  Rearranging the contents 

message: http://www.youtube.com/watch?v=k4RRi_ntQc8 or buried within whole interview http://www.youtube.com/watch?v=1nnj7r1wCD4  —Preceding unsigned comment added by 99.230.244.220 (talk) 01:24, 3 August 2008 (UTC)
thread_title:  Barack Obama on bubble sort 

message: Why does "sinking sort" redirect here? I am aware that NIST says it's the same thing, but go throught "The Art Of Computer Programming" and you will see it's not. I've asked Donald Knuth, the author, about it and he said that he is sure that NIST is wrong and they are currently working on updating their pages with more accurate information and will probably update that as well.
And it's pretty obvious that it's not bubble sort that's named like that, as bubbles don't sink! It sais there what algorithm it actually is. Love4Boobies  —Preceding undated comment was added at 12:15, 25 September 2008 (UTC)
thread_title:  Sinking sort 

message: Hi all. A while ago I began an experiment with a new method for discouraging incorrect good-faith changes to code and pseudocode called "code block templates" on the articles quicksort and binary search algorithm. So far there haven't been any incorrect new changes to those code block templates, but very few changes have been made, so I'd like to expand the scope of this experiment to see how effective it is. This is one of the articles I'm targeting for this second phase. Please let me know on my talk page if you have any questions or concerns. Thanks! Dcoetzee 21:37, 7 December 2008 (UTC)
thread_title: Code block templates

message: I think the pseudocode section contains an error. Examining this code block: 
     for each i in 0 to n - 1  inclusive do:
       if A[ i ] > A[ i + 1 ] then
         swap( A[ i ], A[ i + 1 ] )
If the array A is zero-indexed, then when i == n-1 the code references A[ i + 1 ] == A[n] which is outside the bounds of the array. Clearly if A is one-indexed, then there is no entry A[0].
Hgilde (talk) 14:11, 25 September 2009 (UTC)
replies: text:  It is not clear what you are talking about. All three versions appear to work (and have inside and outside loops). The NLM method has a null inside iteration on the last value of the outside loop, but that doesn't stop it from working. Glrx (talk) 15:22, 22 July 2011 (UTC)
replies: text:  i still think that the pseudo-code in the article is incorrect.
current state is
    do{
        swapped = false;
        for(int i = 1; i<=size-1; i++) {
            if(values[i-1] > values[i]) {
                temp = values[i-1];
                values[i-1] = values[i];
                values[i] = temp;
                swapped = true;
            }
        }
    } while(!swapped);
but this will not sort the entire list, as it exits the loop after the first iteration. the final condition ought to be
    
    } while(swapped);
If someone is available for discussion please post your comments here. thanks. --boomSlang 08:54, 8 May 2012 (UTC)

text: That is not the code in the article. The article's loop exit condition is until not swappped -- which is the same as while swapped. Glrx (talk) 14:01, 9 May 2012 (UTC)
thread_title:  Error in pseudocode? 

message: The sinking sort name issue is still with us. See also #Sinking sort above. Sinking sort still redirects here. Sinking isn't mentioned at insertion sort.
I have some trouble with the claim that bubble sort is incorrectly termed "sinking sort". There is a NIST reference that says sinking sort is bubble sort. Knuth says insertion sort is sometimes called sinking sort. We need a reliable source that says bubble sort is not sinking sort. It may be that sinking sort lacks precision and refers to both bubble and insertion methods. In that case, the refs are not inconsistent.
The unsourced arguments are unconvincing. In a bubble sort, the smaller values take their time bubbling up to the surface, but the largest values are rabbits that quickly sink to the bottom. Sinking and bubbling seem equally apt.
Unless there are are reliable sources that says it's wrong to refer to bubble sort as sinking sort, then WP should not make the claim. Hearsay that Knuth said it isn't right isn't verifiable, and NIST has had 4 years to update the page.
Does somebody have an RS that says sinking sort is not bubble sort?
Glrx (talk) 20:48, 21 April 2012 (UTC)
thread_title:  Misnomer 

message: The first and the last paragraph of the article are in direct contradiction about where bubble sort gets its name.  — Preceding unsigned comment added by 213.138.152.225 (talk) 09:31, 27 September 2012 (UTC)
thread_title:  Contradiction in article 

message: I'm not sure about this but i don't think the part which says "until not swapped" is correct. The loop should only end when it reaches the end of the list not when there is no swap. A section of the list could be coincidentally in order and this may stop the loop prematurely. E.g. 127935. 1 and 2 would produce no swaps at all and end the 'repeat...until' loop prematurely. 60.51.124.251 (talk) 10:37, 14 March 2013 (UTC)
replies: text: The end condition for the repeat...until is only tested after the for loop has examined the entire list. Glrx (talk) 04:26, 15 March 2013 (UTC)
thread_title:  Pseudocode Correct? 

message: sometimes i think its possible to swap two equal size blocks as some generalization of bubblesort. Using Euclid arrange/rearrange there could b possible that those two blocks have different sizes.... Florin Matei, Romania 93.118.212.93 (talk) 03:58, 22 June 2013 (UTC)
thread_title:  a possible useful 1 -> k, k practically any value 1..n data extrapolation 

message: This is the basic sort for programmers and the external links contain all languages Except C.So I posted an additional link for a C implementation of Bubble sort [www.loverusham.blogspot.in/2014/03/bubble-sort-selection-sort-insertion.html Bubble Sort in Basic C] in Basic C but it has been reverted by some Spambot.I am new here and I dont understand how it works.  — Preceding unsigned comment added by LoverushAM (talk • contribs) 06:59, 14 March 2014 (UTC)
replies: text: The clue is in the URL.  "blogspot" is a blog which is not regarded as a reliable source for Wikipedia purposes.  I have no doubt that the C algorithm is correct, but sourcing it from a blog is not regarded as acceptable.  DieSwartzPunkt (talk) 14:59, 21 March 2014 (UTC)

text: Ah, I have just spotted what the real problem is.  The blog in question was published by yourself, so it is regarded as a self published source which is not acceptable.  The bot spotted that your account name is also in the URL of the blog.  DieSwartzPunkt (talk) 15:06, 21 March 2014 (UTC)
thread_title:  No External Links to Implement Bubble Sort in Basic C language 

message: Why does the Exchange sort redirect to this article?  It has no relationship to the bubble sort being a completely different algorithm.  When compared to the other mainstream sorting algorithms, it comes out as the second fastest for randomised data, taking (very) roughly 50% longer than the Quick sort.  DieSwartzPunkt (talk) 14:56, 21 March 2014 (UTC)
thread_title:  Exchange sort redirects here 

message: This example is misleading. There are 10 comparisons to be made in a list of 5 items: n(n-1)/2. Moreover, if a list to be sorted is in reverse order then the last pass will incur one swap and no further passes will be needed.
Chrysippo (talk) 19:59, 11 November 2015 (UTC)
thread_title:  Step-by-step example 

message: i came across another optimization in _Numerical Methods, Algorithms and Tools in C#_ by Waldemar Dos Passos, starting on Page 304:
https://books.google.com/books?id=oLOB2rvNegUC&pg=PT304&lpg=PT304&dq=%22bubble+sort%22+%22the+last+swap%22&source=bl&ots=P3xGPwUJnq&sig=p37w7-ew-fk_QELw48UrQEpExM8&hl=en&sa=X&ved=0ahUKEwjbnoOugrPJAhXGRSYKHV_FCsI4ChDoAQgiMAQ
it involves moving the lower array bound up when there are no changes to the early part of the list on a pass through.  note that unlike with the upper array bound, this isn't a persistent cap; the lower limit can decrease once a "turtle" drifts down.
somebody smarter than me will have to verify whether this change works, and decide whether the situational speed gain outweighs the added overhead to merit inclusion in the Wiki.  also, because the loop in the book compares (x[i] > x[i+1]) rather than the (x[i-1] > x[i]) in this article, one or more lines of code might need to be adjusted by 1.
(edit: okay, was on a website since 2003: http://www.fredosaurus.com/notes-cpp/algorithms/sorting/bubblesort2.html)  — Preceding unsigned comment added by 73.44.213.60 (talk) 11:20, 8 December 2015 (UTC)
thread_title:  another optimization?  (lower array bound) 

message: I will be removing the last external link added - to a university lecture with one slide that explains the visualization in the infobox. We try to avoid links to lectures. However, the article had no explanation for that visualization and the addition was an attempt to correct that. I've added the original source as a reference in the image caption. In 2007 the author of this style of visualization, disliking sorting animations, ran into "a particularly heinous example of the genre. I found the following specimen on the Wikipedia page for Bubblesort:". So he created his own style of visualization in response to this very page. It was fun finding that out. StarryGrandma (talk) 02:44, 17 March 2017 (UTC)
thread_title:  Removing the last external link added 

message: I am confused by this algorithm.
It uses repeated passes, but this is not necessary.  All that is necessary is to move back one step whenever a swap is done.
Here is JavaScript code that does this:
function sort(list)
{
	for (p = 0; p < list.length - 1; )
		if (list[p + 1] < list[p])
		{
			i = list[p];
			list[p] = list[p + 1];
			list[p + 1] = i;
			if (p == 0)
				p++;
			else
				p--;
		}
		else
			p++;
}
The article claims that the algorithm is very inefficient, but it is highly efficient if it is done the above way.
What is the point of this? Angel Cupid (talk) 04:09, 18 May 2019 (UTC)
replies: text: This is a fun algorithm. What you have given here is not bubble sort, but a version of cocktail sort, which is a bit faster than bubble sort. While your algorithm makes only one upward pass, it will make many downward passes as it moves lower values down. StarryGrandma (talk) 22:40, 18 May 2019 (UTC)
replies: text: Actually this is Gnome sort. StarryGrandma (talk) 22:33, 19 May 2019 (UTC)
thread_title:  Repeated passes are unnecessary 

message: I'm quite sure bubble sort is adaptive, but I can't find anything that would confirm this.  If someone can manage to find this, the section on performance should be rewritten. Binarycat64 (talk) 15:33, 17 June 2022 (UTC)
replies: text: From what i can tell, the definition of an adaptive sorting algorithm is broad enough to include the property of exiting early on a sorted list, so I'm gonna go ahead with the rewrite. Binarycat64 (talk) 15:42, 17 June 2022 (UTC)
thread_title:  bubble sort is adaptive 

message: The Obama section, gives the impression that Obama answered a genuine CS question, whilst the actual video suggests that its staged and for comedic effect. Could/should we reword the sentence to reflect this tone? 
I can see some reasons against editing/adding clarification. Firstly, further detail might place too much focus on Obama, who isn't the focus of the article. Secondly, it might damage Obama character a little. Thirdly, it might be a little awkward to word. PlasticStylus (talk) 19:01, 17 October 2022 (UTC)
thread_title:  Obama's bubble sort answer is staged?