jayati

Sort Colors Dutch National Flag

Feb 25th, 2023
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.59 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     void swap(int &a,int &b)
  4.     {
  5.         int temp = a;
  6.         a = b;
  7.         b = temp;
  8.     }
  9.     void sortColors(vector<int>& nums) {
  10.         int i=0,k=0,j=nums.size()-1;
  11.         while(k<=j)
  12.         {
  13.             if(nums[k]==0)
  14.             {
  15.                 swap(nums[i],nums[k]);
  16.                 i++;
  17.                 k++;
  18.             }
  19.             else if(nums[k]==1)
  20.             {
  21.                 k++;
  22.             }
  23.             else
  24.             {
  25.                 swap(nums[k],nums[j]);
  26.                 j--;
  27.             }
  28.         }
  29.        
  30.     }
  31. };
Advertisement
Add Comment
Please, Sign In to add comment