Sorting an array with alternate smallest-largest values

后端 未结 2 1244
鱼传尺愫
鱼传尺愫 2020-12-21 18:44

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

2条回答
  •  被撕碎了的回忆
    2020-12-21 19:09

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

提交回复
热议问题