Algorithms swapsort

Hello I have a homework question in which I have to determine what values(counter and sortval) are saved at line 14 and 19. at the start sortval =0. from line 7 it is a while loop so 0< 4 (assuming that is the array length) and int counter =0. In the next line it is a for loop so counts from i=0 until 3 incrementing i++. at the if statement sortme[0] < sortme[0] if this is true then counter++. But I do not understand how this happens that counter gets incremented to 1. Why is it counter =1 at line 14?

given is arraySortme{4,2,8,6} and arrayMarkearr{0,0,0,0}

 ``12345678910111213141516171819202122232425`` ``````void swapSort (int* sortMe, int length) { int sortval = 0; bool* markerarr = new bool[length]; for (int i = 0; i < length; i++) { markerarr[i] = false; } while (sortval < length) { int counter = 0; for (int i = 0; i < length; i++) { if (sortMe[i] < sortMe[sortval]) { counter++; } } int tmp = sortMe[sortval]; sortMe[sortval] = sortMe[counter]; sortMe[counter] = tmp; markerarr[counter] = true; sortval = 0; while (markerarr[sortval] == true) { sortval++; } } }``````
Last edited on
 ``123456789`` ``````its the for loop. for( 0, 1,2,3) { if(sortme[0,1,2,3] < sortme[0]) //it does {no, yes, no, no} increment (no, yes, no, no) } is 1 due to ^ ``````
Last edited on
Hello muffins123,

Try moving line 9 outside the while loop. As it is each iteration through the while loop "counter" is first set to zero. By the time you leave the while loop "counter" will equal one. Therefor the last time through the loop "counter is set to zero then one an the while condition fails leaving "counter" equal to one.

Hope that helps,

Andy
Hi thanks for the replies. However I am still confused why counter =1(according to the answer sheet) on the very first loop. On the first loop it's if sortme[0] = sortme[0] then counter++. But that isn't the case here because sortme[0] = sortme[0] =4 which doesn't satisfy the if condition.
it isn't one after 1 iteration of the loop.
it is one on line 14 which is after the for loop (the inner one that increments it) has totally finished.

Last edited on