Hey, so I had this bubble sort method which I have tested and works, but I have to integrate it with another class. I don't understand why it's not actually sorting, would anyone see the issue?
OP, your sort works. Not only do you need to toggle the condition in your test loop, as lastchance said, but you also need to only loop up to (but not including) size - 1 so that the index + 1 is not out of bounds, which would most likely mean you'd be comparing the last actual value to some arbitrary value just past the end.
Hey everyone, so I took this bubble sort method from the textbook, not my code or online, from a textbook and I have to integrate with the code here. It's C I should of said well, I just thought someone here might be able to help.
Thank you to everyone that helped, but just wondering, is that bubble sort I had a bubble sort? I used the text book example for the c one so just wondering is it wrong?
¿why inefficient?
the sorted portion is from 0 to i-1, at each step we insert element array[i]
in the insertion the element is array[j+1], we traverse the array (from i-1 to 0) pushing it down (swaps) until it is in its position (it is not greater than the one to its left, in this case it is descending order)
if the array were sorted the inner loop will break on the first iteration, so only O(n) operations would be done
"Inefficient" insertion sort because each element does a full swap with each lower element on the way down. Where I've seen it before, the temp variable would only be stored for the element moving down, the ones larger than it would all be shuffled up (no swapping) and the moving element (stored in temp) inserted into the sorted place below.
1 2 3 4 5 6 7 8
int j;
for ( i = 1; i < size; i++ ) // int_array[i] is to be moved into sorted part 0, 1, ... , i - 1
{
int temp = int_array[i];
for ( j = i; j > 0 && int_array[j-1] > temp; j-- ) ; // aim to put it in the jth place
for ( int k = i; k > j; k-- ) int_array[k] = int_array[k-1]; // shuffle the rest up (assignment, not swapping)
if ( i != j ) int_array[j] = temp; // put in jth place
}
However, the number of comparisons is the same, so, I guess "very inefficient" was not appropriate here. It just felt like a hybrid of insertion sort and bubble sort with so much swapping.