Bubble Sort
I have two implementations of bubble sort here; one is the model answer and one is mine.
I am just wondering if my implementation would cover every possibility and sort correctly, or if I had somehow misapplied.
18 Replies
Why don't you test it? 🙂
Have you heard of unit tests?
the code is identical
nothing to test
it's far from identical, right?
wdym "far from". one does the
+ 1
in the loop declaration, the other does it in the body
it's identicalthe only difference is that j starts at i + 1 in the second method then (instead of at 0)
and what's
i + 1
when i = 0
?
i would recon that's the same as j + 1
when j = 0
just a hunch
the only thing that's different in the second version is the swapI've heard of them but I don't know how to conduct them
they both yield the same result
I've ran them through arrays
I can see through debugging that the second one (mine) won't loop through as many times as the model answer does
but I consistently get the right answer anyway and I'm confused as to why
The important bit is that the model answer compares j with j+1, and yours compares i with j
Yours isn't bubble sort.
I'm sure there's some input which will trip yours up, trying to find it...
yeah, the way the sort moves isn't the same
I'm not even sure what mine is lol
is it possible to get mine to a reliable output at all?
if not it's fine, I'll just use the default bubble sort
I know mine doesn't implement stuff well
I think yours is solid actually, although I'm not sure what it's called
Isn't their implementation selection sort?
Well, with many more swaps 😅
Yes, I think you're right
Selection sort with many many swaps
But simple selection swap has , no?
I'm not sure what you mean I'm afraid
Ok assuming an ascending ordered simple selection swap, it holds the index of the smallest array value (for that loop) in some variable (I just labelled it SmallestValue).
It then checks across the entire array for values smaller than the value located at arr[SmallestValue], switching indices as it goes along and finds/selects smaller values.
It only performs the swap once it has reached the end of the line and therefore cannot find any smaller values to select.
My question is thus: wouldn't my sort need some sort of selection holder to be considered a selection sort?
But your version doesn't have a separate variable. It uses
arr[i]
as the variable inside the inner loop which holds the smallest item
And it does swaps to change what's in arr[i]
. So it's constantly shuffling the area of the array which is unsorted (but not in a way which affects the outcome), which is why we said it was like selection sort but with lots of swapsBut your version doesn't have a separate variable.That's my point I still dont know why it works 😔 Fluke moment
It works as I just described
It uses
arr[i]
as the smallestvalue
variable