I've been going crazy about this, I watched week 4's lectures, search in here for similar problems, but it seems everyone got pass this step easily. Here's my code (I passed in numbers 5 4 3 2 1)

void sort(int values[], int n)
    int temp;
    for (int i=0; i < n-1; i++)
        int min=i;
        for (int j=i+1; j < n; j++)
            if (values[j] < values [min])
                min = j;
        temp = values[min];
        values[min] = values[i];
        values[i] = temp;

And here's GDB

(gdb) info locals
j = 2
i = 1
(gdb) p values[0]
$4 = 5
(gdb) p values[1]
$5 = 5

i=1, so values[0] must be sorted if the codes worked, but it's all 5 the rest of the array. Because Zamyla says when passed in an array, it's the array itself, so I didn't use pointers here. Please help....


apparently, you're trying to implement selection sort. the problem appears to be with this condition

if (values[j] < values [i])
    min = j;

are you sure you wanna update min every time values[j] < values[i]? for example, consider the array {5, 3, 4}. let's agree that after the first iteration of the outer loop, this array should look like {3, 5, 4} because obviously 3 is the minimum value in the first phase, but let's see what your algorithm does:

  • in the first iteration of the outer loop i == 0. in the first iteration of the nested loop, j == 1. values[j] < values[i] is evaluated to true, so min is set to 1.

  • in the second iteration of the nested array i == 0 and j == 2. values[j] < values[i] is evaluated to true (because 4 is less than 5), so min is updated to 2.

that's a logical error because values[2] which is 4 shouldn't be the minimum value in the first phase.

  • Thank you so much, after reading your answer, I changed 'min=i', and in the second loop, 'if (values[j] < values[min])', then 'min=j'. This way, for everytime the second loop iterate, if the condition is true, it'll update the smaller value and use that value to compare with values[j], but it still get the same result when I run GDB where every value is 5, pls help. again – kenlenney Dec 8 '15 at 14:39
  • @kenlenney did you save your modified source code and recompile? – kzidane Dec 8 '15 at 15:07
  • Yes I did...... – kenlenney Dec 8 '15 at 15:27
  • @kenlenney you may update your original question with the updated code! – kzidane Dec 8 '15 at 15:29
  • just did that like 5 sec ago, tks u so much for your answers and suggestions – kenlenney Dec 8 '15 at 15:32

You must log in to answer this question.

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