I was helping my friend with an assignment and it has been a while since I've used C so I cannot find why this works but the first code works and the second one doesn't. This isn't for the assignment since we figured it out but I want to know why this is happening.
void GnomeSort( int gnomes[], int length ) {
int pos = 1;
while ( pos < length ) {
if ( gnomes[ pos ] >= gnomes[ pos - 1 ] ) {
pos = pos + 1;
}
else {
swap( gnomes + pos, gnomes + pos - 1 );
if ( pos > 1 ) {
pos = pos - 1;
}
}
}
return;
}
This doesn't work:
void GnomeSort( int gnomes[], int length ) {
int pos = 1;
while ( pos < length ) {
if ( gnomes[ pos ] >= gnomes[ pos - 1 ] ) {
pos = pos + 1;
}
else {
swap( gnomes[ pos ], gnomes[ pos - 1 ] );
if ( pos > 1 ) {
pos = pos - 1;
}
}
}
return;
}
The difference is the swap
call:
swap( gnomes + pos, gnomes + pos - 1 );
as opposed to:
swap( gnomes[ pos ], gnomes[ pos - 1 ] );
Here is the Swap function that could not be changed:
void swap(int* ptrA, int* ptrB) {
int temp = *ptrA;
*ptrA = *ptrB;
*ptrB = temp;
return;
}
It is obviously in the input for the swap function, but is it this way? What other ways can you make the input into the swap function?