Sort By Parity | C++ | Straight-forward Solution

A fairly simple and straight-forward solution in C++. O(n) time complexity and O(1) space complexity.

class Solution {
public:
    vector<int> sortArrayByParity(vector<int>& nums) {
        int evenptr = 0;
        
        for(int i = 0; i < nums.size(); i++)
        {
            //Move even to front pos
            if(nums.at(i) % 2 == 0)
            {
                int temp = nums.at(evenptr);
                nums.at(evenptr++) = nums.at(i);
                nums.at(i) = temp;
            }
        }
        return nums;
    }
};
Comments (0)