Move all the negative elements to one side of the array

The problem of move all the negative elements to one side of the array is a common programming task known as partitioning or segregating elements. In this specific case, the goal is to rearrange the elements in such a way. That all the negative numbers appear before (or to the left of) any positive or non-negative numbers in the array.

The task can be seen as a sorting problem. Where the only requirement is to separate the elements based on their negativity rather than sorting them in ascending or descending order. By moving the negative elements to one side, we create a partition in the array that divides the negative and non-negative numbers.

Example for Move all the negative elements to one side of the array

Let’s break down the solution:

  1. The moveNegativeElements method takes an integer array arr as input.
  2. We initialize two pointers, left and right, with the start and end indices of the array, respectively.
  3. We enter a while loop that continues until the left pointer is less than or equal to the right pointer.
  4. Inside the loop, we search for the first positive element from the left side of the array. We increment the left pointer until we find a positive element or until left becomes greater than right.
  5. Similarly, we search for the first negative element from the right side of the array. We decrement the right pointer until we find a negative element or until left becomes greater than right.
  6. If the left pointer is still less than or equal to the right pointer, it means we have found a positive element on the left side and a negative element on the right side that need to be swapped.
  7. We swap the positive and negative elements using a temporary variable, increment the left pointer, and decrement the right pointer.
  8. The process continues until the left pointer becomes greater than the right pointer, indicating that all negative elements have been moved to one side of the array.
  9. In the main method, we create an example array arr and print its original state.
  10. We then call the moveNegativeElements method, passing the array as an argument, to rearrange the negative elements.
  11. Finally, we print the modified array to verify the result.

import java.util.Arrays;

public class NegativeElements {

    public static void moveNegativeElements(int[] arr) {
        int left = 0;
        int right = arr.length - 1;

        while (left <= right) {
            // Find the first positive element from the left
            while (left <= right && arr[left] < 0) {
                left++;
            }
            // Find the first negative element from the right
            while (left <= right && arr[right] >= 0) {
                right--;
            }

            if (left <= right) {
                // Swap the positive and negative elements
                int temp = arr[left];
                arr[left] = arr[right];
                arr[right] = temp;
                left++;
                right--;
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = { -2, 3, -5, -1, 7, 8, -6 };
        System.out.println("Original array: " + Arrays.toString(arr));

        moveNegativeElements(arr);

        System.out.println("Array after moving negative elements: " + Arrays.toString(arr));
    }
}

When you run the code, the output will be:


Original array: [-2, 3, -5, -1, 7, 8, -6]
Array after moving negative elements: [-2, -6, -5, -1, 7, 8, 3]

The time complexity of the provided example for moving negative elements to one side of the array is O(n), where n is the size of the array. This is because the solution involves a single pass through the array using two pointers.

The space complexity of the example is O(1) since it uses only a constant amount of additional space, regardless of the size of the input array. The solution modifies the array in-place without requiring any additional data structures or dynamically allocating memory. Therefore, the space complexity remains constant.

I hope this example helps you understand how to efficiently move negative elements in an array using Java.

Suggestions:

Factorial of a Number Full Explanation With Examples

Check Tree is a BST or not Full Explanation

Postorder Traversal in Binary Search Tree With Full Explanation

Preorder Traversal In Binary Search Tree Full Explanation With Example

Inorder Traversal in Binary Search Tree Full Explanation

Binary Search Tree Traversal With Full Examples And Explanation

Difference Between Binary Tree and Binary Search Tree With Complete Examples

Searching in Binary Search Tree With Full Explanation

Binary Search Tree With Full Explanation And Examples

Minimize the maximum difference between heights

Write a program to cyclically rotate an array by one

Find the Union and Intersection of the two sorted arrays

Move all the negative elements to one side of the array

Next Permutation in c++ || FlutterTPoint With examples

Kth max and min element of an array

Kadaneโ€™s Algorithm In JavaScript With Example

How to reverse an array

Find the Maximum and Minimum element in an Array

Sorting An Array In JavaScript

Donโ€™t miss new tips!

We donโ€™t spam! Read our [link]privacy policy[/link] for more info.

Leave a Comment

Translate ยป
Scroll to Top