No result illustrationNo result illustration

DevLoom

search

Lets Connect

chevron right
Menu
Home

Home

Community

Community

Blog Posts

Blog Posts

Programming

Programming

Tech Topics

Tech Topics

Explore

Explore

Find Jobs

Find Jobs

Tags

Tags

DevLoomPerfect Place for devs
    profile

    Jubair

    upvoteupvote

    0

    downvote

    0

    star

    Moving all the Negative Numbers to left side in the given array

    clock icon

    Asked 11 months ago

    message

    0Comments

    eye

    11 Views

    // Move all -ve Numbers to left side of an Array ! 
    
    // Array  = [1,3,4,5,-4,-3,32]
    
    // our output = [-3,-4,1,3,4,5,32]
    
    #include <iostream>
    #include <vector>
    #include <algorithm>  
    using namespace std;
    
    
    // simple and easy Approch ! 
    
    void moveAllNegToLeft1(vector<int>& nums) {
        sort(nums.begin(), nums.end());   
    
    }
    
    //Optimal Approch ! 
    
    void moveAllNegToLeft2(vector<int>& nums){
    
        int left = 0 ;
    
        for (int i = 0; i < nums.size() ; i++)
        {
           if(nums[i] < 0){
            swap(nums[i], nums[left]);
            left++ ;
    
           }
        }
    
    };
    
    
    // using While Loop ! 
    
    void moveAllNegToLeft3(vector<int>& nums){
    
      int low = 0 , high = nums.size()-1 ;
    
      while(low < high){
    
        if (nums[low] < 0 )
        {
            low++ ;
    
        }
        else if (nums[high]>0)
        {
            high-- ;
        }else{
            swap(nums[low] , nums[high]);
        }
        
      }
    
    };
    
    
    
    
    
    
    
    int main() {
        vector<int> nums = {1, 23, 3, 45, -3, -4, -1, 10};
    
        // moveAllNegToLeft1(nums);
        // moveAllNegToLeft2(nums);
        moveAllNegToLeft3(nums);
    
    
    
        for (int i = 0; i < nums.size() ; i++) {
            cout << nums[i] << " ";
        }
        cout << endl;
    
        return 0;
    }
    
    cpp
    Arrays
    DSA
    medium

    Share

    Write your comment here !

    0 Responses