Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

c - Sorting an array with alternate smallest-largest values

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 smallest element and so on.

But my code just prints the original array and I am not able to figure out why. Any advice would be appreciated.

#include <stdio.h>
void swap(int m, int n);
int main()
{
    int i,j,A[10],n;

    printf ("enter the number of array elements
");
    scanf ("%d", &n);

    for (i=0;i<n;i++){
       scanf ("%d", &A[i]);
    }


    for (i=0;i<n;i++){

        if (i%2 == 0){
            for (j=i;j<n;j++){
                if (A[j] < A[i]){
                    swap(A[i],A[j]);
                }
            }
        }
        else if (i%2 != 0){
            for (j=i;j<n;j++){
                if (A[j] > A[i]){
                    swap (A[i],A[j]);
                }
            }
        }

    }

    for(i=0;i<n;i++){
        printf ("%d
", A[i]);
    }
    return 0;
}

void swap( int m, int n)
{
    int temp;
    temp = m;
    m = n;
    n = temp;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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].


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...