Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Bubble Sort Algorithm?

Im trying to create a simple bubble sort algorithm but cant find any examples. All i need to do is sort a pre defined array of numbers. All the examples i find either don't work or make it unnecessarily complicated. Can someone post me an example of a simple bubble sort (That works) or a link to one.

Thanks in advance :)

3 Answers

Relevance
  • 1 decade ago
    Favorite Answer

    In PHP it would look like this:

    for ($i = 0; $i < count($arr); $i ++)

    {

    for ($j = $i + 1; $j < count($arr); $j ++)

    {

    if ($arr[$i] > $arr[$j])

    {

    $temp = $arr[$i];

    $arr[$i] = $arr[$j];

    $arr[$j] = $temp;

    }

    }

    }

  • Anonymous
    1 decade ago

    Do it your self:

    Bubble-sort(L):

            for i from 0 to lenght(L) - 1:

                    for j from 1 to lenght(L) - i - 1:

                            if L[j -1] and L[j] are in desorder:

                                    swap L[j -1] and L[j]

    Ok, ok, here is an example in Pyhton 3.0:

    def bubblesort(L):

        for i in range(len(L)):

            for j in range(1, len(L) - i):

                if L[j - 1] > L[j]:

                    (L[j - 1], L[j]) = (L[j], L[j - 1])

    words = ["oh", "hi", "mark", "what", "a", "funny", "story"]

    bubblesort( words )

    print( words )

  • 1 decade ago

    http://www.algolist.net/Algorithms/Sorting/Bubble_...

    don't work or make it unnecessarily complicated?

    bubble sort algorithm is very simple and very easy to implement

Still have questions? Get your answers by asking now.