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; 
    }
}
  • I have changed the swap so it is switching the arrays, but it still wont sort correctly – user1475 Jun 24 '14 at 18:41
2

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

| improve this answer | |
  • like i said to juan: good point but it still did not fix the problem. – user1475 Jun 24 '14 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 '14 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]

| improve this answer | |
  • good point but it still did not fix the problem. – user1475 Jun 24 '14 at 3:22
  • not necessarily. what about a random sequence of numbers users enter – user1480 Jun 24 '14 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 '14 at 8:49
  • it still wont sort correctly – user1475 Jun 24 '14 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? – Juan Carlos Piñeros Jun 25 '14 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;
} 
| improve this answer | |
  • not sure what you mean. – user1475 Jun 24 '14 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)

| improve this answer | |
  • 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 '14 at 20:56

You must log in to answer this question.

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