Given an array I am required to sort it in such a way that the first element is the smallest value, the second element is the largest, the third element is the second smalle
You need to pass by reference using pointers.
void swap( int *m, int *n)
{
int temp;
temp = *m;
*m = *n;
*n = temp;
}
and change your code to call it like this
swap (&A[i],&A[j]);
For a solution that doesn't use pointers you can use a MACRO like this;
#define swap(x,y) do{int t=(x);(x)=(y);(y)=t;}while(0);
swap(A[i],A[j]);
Just define this at the top of your file and remove the swap function and prototype. It's all about scope, because the MACRO is just a text replace it's in the correct scope to use A[i].
The first problem I notice in your program is your swap function. In your swap function, your parameters are primitive data types. Thus, the function creates copies of integers "m" and "n", and switches the values within the scope of the function swap
. But as soon as the function returns, you haven't really swapped anything. To actually swap the values in the array that you created in main, you need to do a pass by reference(pass in pointers to the variable you are trying to swap). Modify your swap function like this:
void swap( int *m, int *n)
{
int temp;
temp = *m;
*m = *n;
*n = temp;
}
Then inside your main, pass in the address of that value in the array using the &
operator(address of). Here is an example: swap (&A[i],&A[j]);
Other suggestions: