moorecm wrote: |
---|
However, I'm not clear on why the bubble sort snippet above has three nested for loops. |
Because that's not bubble sort. It's the sort I came up with (just about) before I know any formally taught ones. I think it's still O(n
2) though. The inner-most loop is only to insert the element into the correct place. And on that alone I believe this is a form of insertion sort, but I'm not exactly sure. It did run faster then both bubble and selection on large randomly generated arrays (1000+ elements) when I tested it. But you all are free to post your results also. I agree that the sort above is a bit lengthy-er then bubble sort, but the point was it is likely that given the opportunity, someone's intuitively implemented sort could be faster, teach them about implementing a real-world algorithm in code, and allow them to really remember
why the sort works.
Just FYI: my new version I use now uses a binary search instead of a linear search for the second loop, taking advantage of the fact that all the elements the the left of
rPos
are in order. And If you use this on a standard container like vector<T>, you can replace the inner insertion loop with methods like
vec.insert( ... )
and
vec.erase( ... )
jsmith wrote: |
---|
I think that if a newbie was to invent a sort by himself/herself knowing nothing of the sorts that are available, the selection sort would be the algorithm s/he comes up with first. |
I agree. I also think that's a fine sort to start with.
jsmith wrote: |
---|
when I was learning sort algorithms in college, bubble sort was perhaps the "simplest" to remember. |
I remember algorithms by how they work and what they accomplish, not by how to write the exact code. This may come from the fact that I'm strong in more then one programing language.
Gray Wolf wrote: |
---|
Simplicity and intuitiveness don't always go hand in hand. |
[Bubble sort] doesn't have to be intuitive because you are given it. |
True, but perhaps it is easier to learn and remember something that's intuitive then something that's a bit more foreign.
Also
Gray Wolf I don't think that most people are learning about linked lists before they learn about sorting. Sorting is just needed more often.