Puzzle: Sort an array of 0's and 1's in one parse.

后端 未结 6 794
情歌与酒
情歌与酒 2020-12-31 16:00

Is it possible to arrange the array made up of only 1\'s and 0\'s in descending order within one parse without using auxiliary array?
For example: Suppose you have an ar

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-31 16:46

    Let me try this:

    void arrange(int a[],int n)
    {
        int* p = a;
        int* q = &a[n-1];
    
        while (p <= q) 
        {
            while (*p == 1 && p <= q) /* Find a Zero, starting from the front */
            {
                ++p;
            }
            while (*q == 0 && p <= q) /* Find a One, starting from the back */
            {
                --q;
            }
    
            if (p < q) /* *p == Zero, and *q == One, and p is to the left of q. */
            {
                *p = 1; 
                *q = 0;
            }
        }
    }
    

    This works with two pointers, one starting at the front, the other starting at the back, and they both move towards the middle until they meet.

    Along the way, if the two pointers find a 0 on the left and a 1 on the right, swap the values, then continue.

    (code is untested, but the outline seems solid)

提交回复
热议问题