This code is leading me to an infinite cycle and I can’t figure out why

Asked

Viewed 71 times

-1

This code is leading me to an infinite cycle and I can’t figure out why.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void
troca (double *n1, double *n2)
{
    double n;

    n    = *n1;
    *n1  = *n2;
    *n2  = n  ;
}

void
ordena (double *r, int size)
{
    int t;
    int i;

    while (1)
    {
        t = 0;
        {
            for (i=0;i<size-1;i++)
            {
                if(r[i] > r[i+1])
                {
                    troca (&r[i], &r[i+1]);
                    t      = 1          ;
                }
            }
        if(t == 0)
            break;
        }
    }
}


int
main(int argc, char **argv)
{
    FILE   *f1   ;
    int    i     ;
    int    j=0   ;
    int    N     ;               
    int    k     ;             
    double Min   ;
    double Max   ;
    double *reais;           
    double n     ;
    char    c    ;

    sscanf(argv[1],"%d",&N)   ;
    sscanf(argv[2],"%lf",&Min);
    sscanf(argv[3],"%lf",&Max);

    f1    = fopen("f1.txt", "wb")            ; 

    srand(time(NULL));

    while (1)
    {

    if (j == 0)
    {
        reais = (double*)malloc((N)*sizeof(double));
        j=1;
    }

    else
        reais = realloc(reais, (N)*sizeof(double));

    n = Max - Min;
    for (i=0;i<N;i++)
    {
        reais[i] = Max - ((double) rand()/(double) RAND_MAX )*n;
        //printf("%9lf",reais[i]);
    }

    ordena(reais, N);

    k = 0;
    for (i=0;i<N;i++)
    {
        printf("%9lf",reais[i]);
        k++;

        if (k == 5)
        {
            k = 0;
            printf("\n");
        }
    }

    printf("\nDeseja repetir as operacoes:\n1-Repetir\n2-Sair\nR:");
    c = getchar();

    if (c == '1')
    {
        printf("\nIntroduza novos valores de N, Min e Max:");
        scanf("%d %lf %lf", &N, &Min, &Max);
        continue;
    }

    if (c == '2')
    {
        free(reais);
        break;
    }

    }

    return 0;
}

The program takes three arguments from the command line, N, the number of reals the user wants to generate, Max and Min the limits of the generated values. With these values is generated a vector of doubles with the necessary size that is then ordered. So far everything works well. The problem is that when I ask for new arguments, I enter an infinite loop

  • Dude, first tell me what you intend to do.. with these variable names, you can’t understand anything. Plus, there are 2 while(1) in the code, one of which is enough to throw you into an infinite loop.

  • The program takes three arguments from the command line, N, the number of reals the user wants to generate, Max and Min the limits of the generated values. With these values is generated a vector of doubles with the necessary size that is then ordered. So far everything works well. The problem is that when I ask for new arguments, I enter an infinite loop.

2 answers

0

You are ordering using the bubble strategy, with right to a flag to mark whether there have been exchanges or not.

Mathematically, you need to do the most o( (n^2 - n)/2 ) operations. By rotating once the inner side, there is a guarantee that the largest number will be at the end of the vector. Then the next sorting bid would not need to go to the last position, only to the penultimate, then the two largest elements will be in their definitive positions. In that reply, called this strategy of minimizing the amount of repetitions of "minimal bubblesort". You can put the flag to indicate that if there was no swap, then the vector is already ordered and no longer need to work on it.

This operation the way you’re doing is slow. Don’t be surprised by it. My suggestion for improvement at best doubles the speed, but also remains slow (more relative performance information on another linked answer).

In theory, his ordination would one day end up considering that the exchange operation is correct and that the comparison is correct. I couldn’t see any problems with these operations. If you want to do a debug, but do not have the most traditional tools for it, you can insert a printf to indicate when there is exchange and what are the values being exchanged. Obviously this would be a debugging code that should be removed in the final version.

Then, the loop failure must be at another point. The other loop there is at the main function. You are using the getchar(). What happens if this function returns a value you don’t expect? From what I understand of the code, it returns the loop weakly, without changing any of the parameters.

Or maybe he just isn’t reacting to you typing? According to function reference, it only returns the moment you press ENTER. It wasn’t clear to me what happens if you happened to read something earlier.

  • I already managed to fix it, I forgot to clean the buffer after every use of getchar(), which is why there were strange things going on

0

If I understand the code correctly the problem is in the method ordena; how do you have a for covering all the positions of the r, doesn’t need the while(1).

The loop was because the t == 0 never occurs, since whenever you enter the iteration for (i=0;i<size-1;i++) this guy spins and the t = 1; also.

voi ordena (double *r, int size)
{
    int t = 0;

    for (int i = 0; i < size - 1; i++)
    {
        if (r[i] > r[i+1])
        {
            troca (&r[i], &r[i+1]);
            t = 1;
        }
    }
}

OBS: I kept the structure of the variables and such, but tries to use more intuitive names, it is much easier to understand the code.

Besides, there are some things to improve, for example the FILE *f1;. You just create this variable and open a file, but use it for nothing.

  • I know I haven’t used the file yet, I was just testing this particular part. I don’t think the problem is because of this function because the infinite loop occurs after it acts.

  • @Vascopinhão tested the method ordena so?? Still looping? If so, add printf() at points you think it can be, helps to identify.

  • I must disagree about the infinite tie in ordination. In theory, with the swap and the comparison operation working as expected, will end after a few size^2 - size comparison operations

Browser other questions tagged

You are not signed in. Login or sign up in order to post.