my bubble_sort doesn't work correctly

I have here a Bubble Sort algorithm implemented, from pseudo code from this site: http://faculty.cs.niu.edu/~hutchins/csci241/sorting.htm

But the last element will not get sorted. So could someone check if the error is at the pseudo code or if I have it wrong implemented.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <stdio.h>
#include <stdlib.h>


 void bubble_sort( int *arr,  int *end)
 {
     const int SIZE = end - arr;
     
     for( int i = 0;  i < SIZE-2;  ++i)
     {
         for( int k = 0;  k < SIZE-2; ++k)
         {
             if( arr[k] > arr[k+1])
             {
                 int tmp  = arr[k];
                 arr[k]   = arr[k+1];
                 arr[k+1] = tmp;
             }
         }
     }
 }

int main()
{
    const int SIZE = 10;
    const int SEED =  0;
    
    int arr[SIZE];
    
    srand(SEED);
  
    for( int i = 0;  i < SIZE;  ++i)
    {
        arr[i] = rand() % 10;
        printf( "%d%c ", arr[i], i < SIZE-1?',':' ');
    }
    
    bubble_sort( arr,  arr + SIZE );
    
    printf("\nsorted to:\n");
    
    for( int i = 0;  i < SIZE;  ++i)
        printf( "%d%c ", arr[i], i < SIZE-1?',':' ');
        printf ( "\n" );

    return 0;
}
Why SIZE-2 on both loops? How will you ever access arr[SIZE-1] if k+1 == SIZE-2 when the loop ends?

Instead of randomly generating 10 numbers, keep it simple: start with just 3 numbers.

1
2
3
    const int SIZE = 3;
    int arr[SIZE] = {3, 2, 1};
    bubble_sort( arr,  arr + SIZE );


Then, do the logic by hand or use a debugger to iterate through your bubble_sort function.

Edit: Looking at the pseudo-code you linked. The "to" in that pseudo code means inclusive last number.
Try doing <= SIZE-2 or < SIZE-1.
Last edited on
Here is a slightly more optimized version of the bubble sort.
https://www.youtube.com/watch?v=6Gv8vg0kcHc
1
2
3
     for( int i = 0;  i < SIZE - 1;  ++i)
     {
         for( int k = 0;  k < SIZE - 1 - i; ++k )    // -i is optional, but avoids wasting time on what's already sorted 


You can also optimise further by having a boolean variable tell you whether you made any swaps on a particular pass (i.e. value of i). If you made no swaps on that pass then the whole array is sorted and you can catch an earlier train home.
Thx, what a lapse, I could't even interpret some pseudo code ;)
Topic archived. No new replies allowed.