Arman Iqbal
Arman Iqbal

Reputation: 755

Why is my program not sorting the struct?

I am trying to create this program that takes an int number from the user then randomizes a pair of numbers, based on the input, inside the an array of struct. Then it sorts this array based on the sum of the number pair the program randomized.

However my program won´t sort the array of struct. It doesn´t do the sorting properly and Im not sure why. Here is the code.

#define MAX 10

struct NumPair{
int n,m;
};

int main()
{
    int i, j, amount=0;
    NumPair NumPair[MAX];

    srand(time(NULL));

    printf("How many pair of numbers? (max 10): ");
    scanf("%d", &amount);

    for (i=0; i<amount; i++)
    {
        NumPair[i].n = rand() % 11;
        NumPair[i].m = rand() % 11;
    }

    for (i=0; i<amount; i++)
    {
        for(j=1; j<amount; j++)
        {
            if( (NumPair[i].n+NumPair[i].m) > (NumPair[j].n+NumPair[j].m) )
            {
                int tmp;

                tmp = NumPair[i].n;
                NumPair[i].n = NumPair[j].n;
                NumPair[j].n = tmp;

                tmp = NumPair[i].m;
                NumPair[i].m = NumPair[j].m;
                NumPair[j].m = tmp;
            }
        }
     }

     for (i=0; i<amount; i++)
     {
        printf(" NumPair %d: (%d,%d)\n", i+1, NumPair[i].n, NumPair[i].m);
     }
return 0;
}

What am I missing? It's probably something very silly.

Thanks in advance.

Upvotes: 0

Views: 54

Answers (3)

BLUEPIXY
BLUEPIXY

Reputation: 40145

change to

for (i=0; i<amount-1; i++){
    for(j=i+1; j<amount; j++){

Upvotes: 0

this
this

Reputation: 5290

You are comparing iterators i with j. Bubble sort should compare jth iterator with the next one

for (i=0; i<amount; i++)  //pseudo code
{
    for(j=0; j<amount-1; j++)
    {
        if( NumPair[j] > NumPair[j+1] )  //compare your elements
        {
             //swap
        }
    }
 }

Note that the second loop will go only until amount-1 since you don't want to step out of bounds of the array.

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881093

Your algorithm is incorrect. This little snippet:

for (i=0; i<amount; i++) {
    for(j=1; j<amount; j++) {

will result in situations where i is greater than j and then you comparison/swap operation is faulty (it swaps if the i element is greater than the j one which, if i > j, is the wrong comparison).

I should mention that (unless this is homework or some other education) C has a perfectly adequate qsort() function that will do the heavy lifting for you. You'd be well advised to learn that.

If it is homework/education, I think I've given you enough to nut it out. You should find the particular algorithm you're trying to implement and revisit your code for it.

Upvotes: 2

Related Questions