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

后端 未结 6 795
情歌与酒
情歌与酒 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:44

    Give it a try!

    (read comments):

    #include
    int main(void){
        int a[]={1,0,0,0,1,0,1};
        int n = 7,
            i,
            index = 0;
    
       while(index < n && a[index]) index++; // skip initial 1's
       for(i = index; i < n; i++){  
         if(a[i]) a[index++] = 1; // if `1` at a[i] make its 0 and
         a[i] = 0;                // make at index 1. 
       }
    
       for(i = 0; i < n; i++){
            printf("%3d", a[i]);
       }
        return 1;
    }
    

    Check working code @ideone's links:

    Case-1: {1,0,0,0,1,0,1}
    Case-2: {1,0,1,1,1,0,0,1,0,1, 1}
    Case-3: {1,1,1,1,1,1,1}
    Case-4: {0, 0, 0, 0, 0, 0, 0}
    Case-5: {0, 0, 0, 1, 1, 1, 1}

    So I think it works correct!
    its simple, it need only n iterations.
    complexity wise O(n).

提交回复
热议问题