I just checked my code for Pset3 finds less confortable and it works but I am puzzled by some of the printf I put to debug my code. I put this just at the end of my sorting function:

     printf("%i %i %i %i\n", values[0],values[1],values[2], values[3]);

And this is the compiling result

    ~/workspace/pset3/find/ $ ./find 42

    haystack[0] = 11 

    haystack[1] = 33

    haystack[2] = 22

    haystack[3] = 42

    haystack[4] = 
    0 33 22 42
    0 11 33 42
    0 11 22 42
    0 11 22 33
    0 11 22 33

Why is values[0] printing a 0? if I modify and start my loop at 1 it shifts the zero to index 1.

Here is the full code:pastebin

If anyone have a clue, I would be curious to know. Thanks,

  • Why do we need to guess? Isn't it more logical to show your code for sort? – obesman Jul 10 '17 at 17:09
  • Hi @obesman, thanks for the answer, fixed it above. – Guillaume_slize Jul 10 '17 at 18:54

Whenever an unexpected value, particularly 0, suddenly appears in the sorted list and the largest value disappears, look for code that goes beyond the end of the array.

This is a somewhat common error. The code is going past the end of the array and picking up what it thinks is another element. Usually, this turns out to be 0, and gets sorted to the beginning, while the largest element gets sorted out the end.

You might think that this would generate an error, but it doesn't. This ability was long ago intentionally included in C as a tool to manipulate arrays and sub-arrays.

Look at the following code:

for(int i=0;i<=n;i++){
    for(int j=i+1;j<=n;j++){
        if (values[i]<=values[j]){

Remember that there are n elements in the array, numbered from 0 to n-1. This code will eventually process values[n] when both i and j are n. This is were it's going off the rails.

Also, you might benefit from a review of the class material on bubble sorts. When comparing array elements, one of the loops needs only to go to n-1 and the other to n-2.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

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