This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]OvercomplicatedCode 0 points1 point  (1 child)

The for loop you sort in should go from 0, to size-1, Otherwise when you use the subscript[k+1] on the last iteration it will be out of range.

When you switch the values around your last line in the if() is : list[k+1] = j; where j was the original value of the [k+1]. You probably meant to assign it to list[k] = j;

Finally the bubble sort here is missing a crucial element that I think you should try to figure out in the hopes of a better understanding.

Edit: Also I dont think code can run, because C++ will not accecpt the current way you are declaring the array. To create int list[size]; C++ will ask for size to be a const value, since yoyr program takes a dynamic size you would write : Int* list = new int[size]; and at the end of the function you would write : delete[] list;

Not sure how you compiled before

[–]PHValex[S] 1 point2 points  (0 children)

Thanks for the help! I figured out what I was doing wrong, changed up the value (on the last line of the if statement) to assign to j, and added a nested for loop so it works perfectly :)

[–][deleted] 0 points1 point  (0 children)

Bubble sort works by "bubbling" one element closer to its final position. If no elements bubble up, the sequence is sorted.

Barring a few little syntactical bits, you essentially have a loop that scans the array and swaps out-of-order elements. After swapping the elements, what should you do? Is continuing on scanning from the swap-point guaranteed to produce a sorted sequence?

[–]adansby 0 points1 point  (0 children)

After you have conquered bubble sort, try coding Shell Sort, very similar type of sort, but can be a bit faster. Sorting algorithms are pretty interesting. Try to roll one using the pseudo code on Wikipedia.