Sorting an array with alternate smallest-largest values

后端 未结 2 1240
鱼传尺愫
鱼传尺愫 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:27

    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:

    1. Format your code so there is space between your conditions in your for loops.
    2. Add comments.

提交回复
热议问题