# What's wrong with my sort function?

I can't figure this out, and its been driving me nuts. Can anyone help me see what I've done wrong? Headers are ommitted

``````void sort(int values[], int n)
{
//TODO: implement an O(n^2) sorting algorithm
// iterate through each int in the array, check if it is larger
// than the next number, swap them if it is.

// n = elements in the array
// i = element being inspected
// j = element that is next in array after i
for (int i=0; i<n; i++)   //iterate through each integer
{
int min = i;
for (int j=i+1; j<n; j++)   //iterate through succeeding integers
{
if (values[j]<values[i]) //if one is less than first...
{
min = j; //...make it the new minimum
}
}
int temp = i;           //save value of i
values[i] = values[min];    //replace int with minimum
values[min] = values[temp]; //swap in the original value of i
}
}
``````

1) You're not swapping variables, instead, you're overwriting all variables with the smallest one.

``````int temp = i;
values[i] = values[min];    //replace int with minimum
values[min] = values[temp];
``````

Suppose that i == 0 and min == 10 (the value there was 1, for example).

``````int temp = i; // now temp == 0

values[i] = values[min];  // now values[0] has the value 1

values[min] = values[temp];
``````

// now values[10] will be set to whatever is in values[temp]. Since temp == 0, now values[10] will have a value of 1 too.

Go back to the swap video by Prof. Malan and take a look at exactly how you're meant to swap values.

• I don't understand exactly. So in your example are both values[i] and values[10] initially 1? Oct 31 '15 at 21:50
• would replacing those three lines with this work?: int temp = values[i]; values[i] = values[min]; values[min] = temp; however the code still doesn't find the needle. Oct 31 '15 at 21:58
• No, in my example initially they would have different values. They end up with the same value because you initialize temp to 'i' , you assign the minimum (1) to values[0] and you also assign whatever is in values[0] to vallues[min] The second swap seems correct. Have you tried debugging with gdb? Oct 31 '15 at 22:15
• I've been trying, but I'm still learning gdb at this point. I'll keep trying though! Oct 31 '15 at 22:32
• I figure it out, thanks! Nov 1 '15 at 0:55