0

Similar questions asked many times but I'm working on this endlessly without success so need your help

void sort(int values[], int n)
{
    // TODO: implement an O(n^2) sorting algorithm
    int i,j,k,tmp;

    for(j = 0; j < n-1; j++)
    {
        for(i = 0; i < n-j-1; i++)
        {
            if(values[i] > values[i+1])
            {
                tmp=values[i];
                values[i]=values[i+1];
                values[i]=tmp;
            }
        }
    }
    for (k = 0; k < n; k++)
    {
        printf("\n");
        printf("no%d: %d",k,values[k]);
    }
    return;
}

last printf indicates my list is not sorted. I am compiling find.c with generate.c

1 Answer 1

2

You have such a little mistake, but that mistake ruins all your work. Look here:

tmp = values[i];
values[i] = values[i+1];
values[i] = tmp;

The last line values[i] = tmp should be values[i+1] = tmp if you want to switch those two variables. I'm sure you knew this and this is just a typo.

I don't know why was your question downvoted. To me in looks like a really good question, much better than others I've seen. Good job with your code. Check for yourself if that fixes your problem.


If this answers your question please accept it by clicking the gray check-mark to the left, so that it becomes green. You can also vote it up by pressing the up arrow above the check-mark. And don't forget to keep coding!

1
  • 1
    I can't believe I made such a stupid typo . I thought I was swapping correctly so I didn't look that part. I was focusing loops all the time. Thank you very much, you're always helping! Commented Sep 10, 2015 at 19:18

You must log in to answer this question.

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