If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To move all negative numbers to the left side of an array, you can use the Two-Pointer technique. The idea is to maintain two pointers, one at the beginning of the array (left pointer) and another at the end of the array (right pointer). The left pointer will move towards the right, and the right pointer will move towards the left until they meet.
Here's the algorithm to achieve this:
- Initialize two pointers
leftandright, whereleftis set to the beginning of the array (index 0), andrightis set to the end of the array (indexn-1, wherenis the size of the array).- Repeat the following until
leftis less than or equal toright: a. If the element at theleftpointer is negative, moveleftpointer one step to the right. b. If the element at therightpointer is positive, moverightpointer one step to the left. c. If the element at theleftpointer is positive and the element at therightpointer is negative, swap the elements atleftandright, and then move both pointers one step to the right and one step to the left, respectively.After the above steps, all the negative numbers will be on the left side of the array, and all the positive numbers will be on the right side of the array.
Here's the C++ code to implement the algorithm:
cppCopy code
#include <iostream> #include <vector> void moveNegativesToLeft(std::vector<int>& nums) { int left = 0; int right = nums.size() - 1; while (left <= right) { if (nums[left] < 0) { left++; } else if (nums[right] >= 0) { right--; } else { std::swap(nums[left], nums[right]); left++; right--; } } } int main() { std::vector<int> nums = {-1, 2, -3, 4, -5, 6, -7, 8}; std::cout << "Original Array: "; for (int num : nums) { std::cout << num << " "; } std::cout << std::endl; moveNegativesToLeft(nums); std::cout << "Array after moving negatives to the left: "; for (int num : nums) { std::cout << num << " "; } std::cout << std::endl; return 0; }Example Output:
sqlCopy code
Original Array: -1 2 -3 4 -5 6 -7 8 Array after moving negatives to the left: -1 -7 -3 -5 4 6 2 8In this code, the
moveNegativesToLeftfunction rearranges the array so that all negative numbers appear on the left side. The time complexity of this algorithm is O(n), where n is the size of the array.

I bought this course, it worth it!

Hi i want to buy this course but you dont have master card payment method please let me know how i can buy it

Dear mk.info.work, Now we have all types of payment options. If you need to purchase just checkout our official website
Quick answers to common questions about our courses, quizzes, and learning platform
Didn't find what you're looking for?
Contact Support
SCIAKU Team please upload 1st video of TREE please please please, please