0

I'm pulling my hair over the bubble sorting code that just won't work. Here is my pseudocode:

for all elements in list size n excluding the last elements
   if values(i) > values(i+1)
     swap values(i) and values(i+1)
     recognize that the list is swapped
   if the list is not swapped after iteration
     break

and the code implementation is:

    void sort(int values[], int n)
{
    void bubble(int values[], int n);
}

void bubble(int values[], int n)
{
    int hi = n - 1;
    bool swapped;
    // for all elements in the list
    for (int a = 0; a < hi ; a++)
    {
        for (int b = 0; b < hi-a; b++)
        {
            if (values[b] > values [b+1])
            {
                int temp = values [b];
                values[b] = values[b+1];
                values [b+1] = temp;
                swapped = true;
            }
        }
        if (swapped == false)
        {
            break;
        }
    }
}

but when I try to print the result of sort(haystack, size), I got this:

sort(haystack, size);
for (int k =0; k < size -1; k++)
{
    printf("%i\n", haystack[k]);
}

haystack[0] = 34

haystack[1] = 65

haystack[2] = 88

haystack[3] = 23

haystack[4] = 25

haystack[5] = 64

haystack[6] = 
34
65
88
23
25

The list was not sorted AND lose the last elements as well.Can anyone kindly point out my wrongs? Thanks alot.

0
1
void sort(int values[], int n)
{
    void bubble(int values[], int n);
}

Here you just declare bubble function, but don't call it. Strange that you do not get an error like "unused parameter" while compiling.

Try this:

void sort(int values[], int n)
{
    void bubble(int values[], int n);
    bubble (values,n);
}

and you do not lose this last element, you just do not print it, as your loop for size - 1 elements, not for size.

4
  • Thanks but do you know why my function just doesn't sort? Any logical faults?
    – Ha Tran
    Jun 14 '17 at 6:00
  • it sorts! all logic is fine, bubble function is working. but sort need to call bubble. Does it work now with changes that i offered?
    – obesman
    Jun 14 '17 at 6:04
  • Yass it works now. Thanks a lot!!!
    – Ha Tran
    Jun 14 '17 at 6:37
  • Great ) happy coding!
    – obesman
    Jun 14 '17 at 6:42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .