After diving into pset3 I have stumbled upon one particular problem. In 'Search' problem we are supposed to write program that will sort values and afterwards search for the requested one. As far as I understood values in for loop (see below) are being overwritten, not swapped (which is ultimate goal, so to speak). Are there any methods to concatenate values to the array, because overwriting them won't bring anywhere?

void sort(int values[], int n)
   //overrides values[i] with minimum values, no concatenation to array
   for(int i = 0; i < n;i++)
     int tmp = values[i];

     if(values[i] > values[i+1])
            values[i] = values[i+1];
            values[i+1] = tmp;

  • What happens when i = n - 1? – Sam Gerber Oct 13 '15 at 16:01

Say your array is 3,2,1

On the first pass of your loop (i = 0) your array will become: 2,3,1

Then i becomes 1 and on the second pass it will become: 2,1,3

This is good, as now the 3 is in the right spot.

But now i is 2 and your loop will compare 3 with the null terminator and swap those.

Then your loop will end with your array essentially being 2,1,\0,3

Clue: What you need to do is wrap the loop you have there inside another that will keep running the internal loop but without re-sorting the already sorted values at the end of your array. Maybe by shortening the length of the array each time by one...? Watch this animation closely and it may help

Hope this helps

You must log in to answer this question.