views:

1170

answers:

7

What is a bubble sort? Can someone help me?

Edit-

See also this earlier question: What is a Bubble Sort good for? Although very similar, "What is a bubble sort?" is a more fundamental question and is therefore still useful for beginners to programming.

A: 

A bubble sort is a simple, though inefficient, means of sorting a list of data by continually passing through the list, swapping pairs of elements that are out of order. You can implement it something like this in Java (assuming you have an integer array, 'data', which contains the data to be sorted):

  for (int passNo = 0; passNo < data.length; passNo++) {
    int maxPos = data.length - 1 - passNo;
    boolean swapped = false;
    for (int i = 0; i < maxPos; i++) {
      int d0 = data[i];
      int d1 = data[i+1];
      if (d1 < d0) {
        data[i] = d1; data[i+1] = d0;
        swapped = true;
      }
    }
    if (!swapped)
      break;
  }

The sort is thus so-called because a given piece of data gradually "bubbles" over the array until it reaches its correct place. The loop over 'i' does the "bubbling". It compares all consecutive pairs of ints, swapping any that are out of order. We need to repeat this process a maximum of 'n' times, where 'n' is the length of the array (hence the outer loop over 'passNo'). However, if in practice, we do a pass where no pair of data is swapped, then we know that the data is sorted, hence the 'swapped' variable.

Bubble sort is an inefficient means of sorting data and is practically never used. Pretty much its only redeeming feature is that it is simple enough for your granny to understand. If for some reason you find yourself stuck with your laptop on a desert island with no access to any other sort library, it might be the sort routine you can remember.

As with inefficient sort algorithms in general (compare the insertion sort), the inefficiency comes from the fact that we end up comparing the same pairs of data many times. More efficient algorithms often use a "divide and conquer" strategy (in one way or another, you divide up the list, sort each sub-part, then stick the sub-parts back together) to avoid having to repeat the same comparisons multiple times.

Neil Coffey
You should probably use the comment form if you're not going to answer the question.
apphacker
Good point. Actually, I'm starting to take it all back, given how many people HAVE answered the question. And I've seen people fed to the dogs for asking much less obviously simple, googlable things. Oh well...
Neil Coffey
And hey, you've now got the opportunity to earn the "peer pressure" badge :-)
John Fouhy
Everything can be found using google. Probably the person who asked the question might not have understood the explanation he found in other site. TStamper has given a good explanation here. It would definitely benefit others.
Mahatma
Question now answered. upvoted.
bendin
+30  A: 

Bubble sort is one of the many sorting algorithms that people use to sort a list.

Worst case performance- O(n^2)

Best case performance- O(n): ironically this only happens if the list is already sorted

Example source code:

void bubbleSort(int numbers[], int array_size)
{
      int i, j, temp;
      int sorted=1;
      for (i = (array_size - 1); i >= 0; i--)
      {
        sorted=1;
        for (j = 1; j <= i; j++)
        {

          if (numbers[j-1] > numbers[j])
          {
            temp = numbers[j-1];
            numbers[j-1] = numbers[j];
            numbers[j] = temp;
            sorted=0;
          }
        }
        if (sorted) { break; } //if done in first loop this it makes best case performance
      }

}

Example of the first loop: array: [45, 67, 12, 34, 25, 39]

In the first step, the focus is on the first two elements which are compared and swapped, if necessary. In this case, since the element at index 1 is larger than the one at index 0, no swap takes place.

45, 67, 12, 34, 25, 39

Then the focus move to the elements at index 1 and 2 which are compared and swapped, if necessary. In this example, 67 is larger than 12 so the two elements are swapped. The result is that the largest of the first three elements is now at index 2.

45, 12, 67, 34, 25, 39

The process is repeated until the focus moves to the end of the array, at which point the largest of all the elements ends up at the highest possible index. The remaining steps result are:

45, 12, 34, 67, 25, 39

45, 12, 34, 25, 67, 39

45, 12, 34, 25, 39, 67

Then repeat the same process starting at index 0;

For more detail here: Bubble Sort

TStamper
+1 for you. Thanks for posting a sample. Seems people forget why this site exists, all kinds of questions should be findable by search engines. And having a code snippet presented is way more preferable than a link (unless there is way more context/info in a link)
Tim Jarvis
So far this is the best one since it answers the question precisely.
SeasonedCoder
Hmm, minor detail: That example lacks the short-circuit on "is-sorted". It'd always be O(n^2).
Tordek
@TStamper, good answer, as this probably going to be mostly for beginners, would it be worthwhile adding an explanation of the "short circuit" in your example?
Ash
@Ash- good point. added it
TStamper
+1 For a good answer, as well as for the diplomatic tenacity and polite response to criticism expressed in the question comments.
Jarret Hardie
A: 

It's an algorithm that sorts in 0 (N^2).

It goes through an array twice, comparing each element of the array to the entire array, and swapping them on some criteria (greater than, lower than).

Its called bubble sort because "heavier" elements go to the "bottom" of the array.

And no, it has no relationship with 1986's Bubble bobble

Tom
It doesn't go through the array twice. The algorithm you describe sounds to me closer to selection sort.
Anzurio
How do you call the accesing the array inside nested for statements ?
Tom
+5  A: 

It's one of the simplest sorting algorithms. It works by swapping consecutive members of a set in the desired order. It is pretty unefficient since it will evaluate each pair once in every run and will rerun through the set until no swapping is necessary.

       do {
            bool ordered = true;
            for(int i = 0; i < values.Length - 1; i++)
                if(values[i] > values[i + 1]){
                    swap(values[i], values[i + 1]);
                    ordered = false;
                }
        } while(!ordered);

One "property" of this sorting algorithm is that, the last members of the set, will be sorted first.

Anzurio
+4  A: 

You can watch it on the traditional Berkeley videos here, among other sort algorithms.

Of course, this is old. But is invaluable!

You must watch the complete Sorting out Sorting series.

eKek0
+1  A: 

Think of the values you're sorting as bubbles that go up depending on the fashion, increasing / decreasing. Technically, values are contained in a list, you iterate the list comparing two values at a time and whichever is smaller / bigger you make it "bubble" up to the top.

Joset