for (int i = 0; i < 4; i ) {
for (int j = 0; j < 4 - i; j ) {
if (array[j] > array[j 1]) {
swap(array[j], array[j 1]);
}
}
}
printf("Descending : ");
for (int k = 4; 0 <= k; k--) {
printf("%d ", array[k]);
}
I made code for descending five typed integer numbers.
And there was two ways for activating this.
The first one is using temp swap in loop(like, tmp=a, a=b, b=tmp
), and second one is declaring swap function(void swap(int x, int y){int tmp=x, x=y, y=tmp}
) and using this func in loop.
First way was successful, but the second way was failed.
I want to know why swap func in loop can't be actuated.
CodePudding user response:
I made code for descending five typed real numbers.
Taking into account the presented code (the used conversion specifier %d
in the call of prinf
) it seems you mean integer numbers not real numbers.
You need to pass the swapped objects to the function by reference indirectly through pointers to them. Otherwise the function will deal with copies of values of the original objects..
The function can be declared and defined for example the following way
void swap( int *a, int *b )
{
int tmp = *a;
*a = *b;
*b = tmp;
}
and can be called like
swap( array j, array j 1 );
or
swap( &array[j], &array[j 1] );