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

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

    #include
    
    using namespace std;
    
    int main() {
        int arr[] = {1, 1, 1, 1, 1, 0, 0, 0};
        int N = sizeof(arr) / sizeof(arr[0]);
        int p = 0, q = 1;
    
    while (q != N) {
        if (arr[p] > arr[q]) {
            arr[p] = 0;
            arr[q] = 1;
            p++;
            q++;
        }
        else {
            q++;
            if (arr[p] == 0)
                p++;
        }
    }
    
    for (int i = 0; i < N; i++)
        cout << arr[i];
    
    return 0;
    

提交回复
热议问题