Bubble Sort (super slow but worth studying) - C++ Solution


  • 0
    A

    The main idea of bubble sort is swaping the smallest ( or largest) element to the end of the array, in this problem, we should swap '0' to the end.

    So here's the code:

    class Solution {
    public:
        void moveZeroes(vector<int>& nums) {
            int i = 0, j;
            for(int i = nums.size() - 1; i >= 0; i--) {
                bool gg = 0;
                int j = 0;
                while(j != i) {
                    if(nums[j] == 0) {
                        swap(nums[j], nums[j + 1]);
                        gg = 1;
                    }
                    j++;
                }
                if (gg == 0)
                    break;
            }
            return;
        }
    };
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.