6
for(int i=0; i<n-1; i++)
{
    for(int j=i+1; j<n; j++)
    {
        if(a[i] > a[j])
        {
            /* Swap a[i] and a[j] */
        }
    }
}

P.S. Given the name of an algorithm, one can easily find relevent source code. But I find it hard to do the vice-versa :D

Edit Oh! If that is bubble sort, then what is the name of this:

for(int i=0; i<n; i++)
{
    for(int j=0; j<n-1; j++)
    {
        if(a[j] > a[j+1])
        {
            /* Swap a[j] and a[j+1] */
        }
    }
}

I thought this second one "bubbles" the smaller elements up, so I thought this was actually bubble sort. If the first one is bubble sort, what's the name of the second one?

2
  • 1
    First is selection sort, second is bubble sort. You were right initially. @everyone who said the first is bubble sort: please rethink that and delete your answers as they are highly confusing coming from people with so much reputation. Commented Mar 18, 2011 at 15:00
  • 3
    I don't mind spamming people with the same thing. It is definitely selection sort. The second one is bubble sort. Commented Mar 18, 2011 at 15:11

4 Answers 4

6

First is the Selection Sort and the second one you added is Bubble sort!

Sign up to request clarification or add additional context in comments.

3 Comments

Finally a good answer. Sorry I had to downvote everyone else however :(. The first one is definitely not bubble sort.
just fresh off an interview :)
You can remember selection sort because it looks through the remaining list and "selects" the best answer. Bubble sort just arbitrarily swaps any items that are out of order in the traversal.
5

First one is selection sort, second one is Bubble sort

2 Comments

@Zoe Gagnon, yes right you are. Funny we all mis-read it as bubble sort. Our collective paranoia about bubble sort triggered!
Honestly, I think selection sort should trigger just as much paranoia as bubble sort. Insertion sort should come with warning labels plastered all over it that say "only use when optimising other sorts". Singling bubble sort out of all the n^2 sorts seems just a little reactionary to me.
3

The name of this algorithm is bubble sort.

edit: sorry for mistake (confused i with j in a[i] > a[j]). The first one is selection sort

Comments

-1

There are so many sorting algorithms. Here are just a few:

  • Selection sort
  • Bubble sort
  • Heap Sort
  • Merge Sort
  • Counting Sort
  • Comb Sort
  • Quick Sort

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.