1

Here is my code:

 for(int i = 1; i < n - 1; i++) {
    printf("%i\n %i\n", i, j);
    int j = i + 1;
    if(values[j] < values[i]) {
            int tmp = j;
            j = i;
            i = tmp; 
    }
}
1
  • I have changed the swap so it is switching the arrays, but it still wont sort correctly
    – user1475
    Jun 24, 2014 at 18:41

4 Answers 4

2

If you are trying to swap the values, you need to be using values[i] and values[j], not i and j.

2
  • like i said to juan: good point but it still did not fix the problem.
    – user1475
    Jun 24, 2014 at 5:16
  • I'm assuming you are doing bubble sort? I've got pretty much identical code and it works fine for me (using values[i] and values[i+1] as the things being swapped). Perhaps your problem is somewhere else.
    – curiouskiwi
    Jun 24, 2014 at 7:33
1

Do you mean:

if(values[j] < values[i]) {
        int tmp = j;
        j = i;
        i = tmp; 
}

or

if(values[j] < values[i]) {
        int tmp = values[j];
        ...
}

?

And maybe values[j] is never less than values[i]

5
  • good point but it still did not fix the problem.
    – user1475
    Jun 24, 2014 at 3:22
  • not necessarily. what about a random sequence of numbers users enter Jun 24, 2014 at 8:16
  • You are swapping i and j, and those are the indexes, not the values, the values are values[i] and values[j]
    – supeindesu
    Jun 24, 2014 at 8:49
  • it still wont sort correctly
    – user1475
    Jun 24, 2014 at 18:40
  • In your line of code printf("%i\n %i\n", i, j); what is the value of "j"? Because it is not initialized yet, is it? Jun 25, 2014 at 13:02
1

Try replacing

if(values[j] < values[i]) 
{
    int tmp = j;
    j = i;
    i = tmp;
}

with

if(values[j]<values[i])
{
   int tmp = values[j];
   values[j] = values[i];
   values[i] = tmp;
} 
1
  • not sure what you mean.
    – user1475
    Jun 24, 2014 at 18:39
1

found the fix!!!!!! it was only going through the numbers 1 time. I fixed it by adding:

for(int a = 0; a < n - 1; a++) {

to the top (and putting a extra } at the end)

1
  • The reason it wasn't working, and why this seemed to fix it, is because your original loop was only going through the array once. Adding this loop around the block of code makes it work, but its messy. You do not need 3 variables for the loop (i, j, and a).
    – m_duran
    Jul 5, 2014 at 20:56

You must log in to answer this question.

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