Asked 5 months ago
0Comments
10 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;
}
Share