Search code examples
cbubble-sort

How to get the reverse order in BubbleSort Algorithm


I was studying this code which is using BubbleSort to get the reverse order(high to low) or the random 20 data that have been inserted in the program. The result should be result (high to low) : 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1.

However, what I get is 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20.

I know that if I change if (data[j] < data[j - 1]) to if (data[j] > data[j - 1]), I can get the right answers.

However, I wish to ask if there is any other way to change the following code to make this give me the reverse order

temp        = data[j];
data[j]     = data[j - 1];
data[j - 1] = temp;

The whole code is as follows:

#include <stdio.h>
#define COUNT 20
 
int main()
{
    int data[COUNT]
        = { 5 , 15 , 7 , 20 , 1 ,
            4 , 10 , 2 , 8  , 11,
            9 ,  6 , 13, 18 ,  3,
            16, 12 , 14, 17 , 19 };
 
    int temp = 0;
    
    printf("random data : ");
    for (int i = 0; i < COUNT; i++)
    {
        printf("%d ", data[i]);
    }
 
 
    //BubbleSort
    for (int i = 0; i < COUNT - 1; i++)
    {
        for (int j = COUNT - 1; j > i; j--)
        {
            if (data[j] < data[j - 1])
            {
                temp        = data[j];
                data[j]     = data[j - 1];
                data[j - 1] = temp;
            }
        }
    }
 
    //print
    printf("\n\nresult (high to low) : ");
    for (int i = 0; i < COUNT; i++)
    {
        printf("%d ", data[i]);
    }
 
    return 0;
  }

Solution

  • One way is inverting the condition. This can be archieved by changing the specified part

    temp        = data[j];
    data[j]     = data[j - 1];
    data[j - 1] = temp;
    

    to

    } else {
    temp        = data[j];
    data[j]     = data[j - 1];
    data[j - 1] = temp;
    

    Another way is reversing the array after sorting. This can be archieved by changing the specified part

    temp        = data[j];
    data[j]     = data[j - 1];
    data[j - 1] = temp;
    

    to

    temp        = data[j];
    data[j]     = data[j - 1];
    data[j - 1] = temp;
    }}}
    for (int i = 0; i < COUNT - i - 1; i++) {{{
    temp = data[i];
    data[i] = data[COUNT - i - 1];
    data[COUNT - i - 1] = temp;