Move all the negative elements to one side of the array in Java

Move all negative elements to one side of the array  in Java

Here, in this page we will discuss the program to move all negative elements to one side of the array in Java . We use the concept of two pointers to do so . We are giving with the size of the array along with array elements.We have to print array as desired

Move all negative elements to one side

Algorithm :

  • Let ‘j’ point to the leftmost positive element in the array. Initially, we set ‘j’ to point to the first element.
  • Iterate over the array:
  • Let ‘i’ be the index of the current element.
  • If the current element is negative:
  • If ‘i’ not equal to ‘j’, then swap the ith and jth elements.
  • Increment ‘j’ by 1.
  • Return the resulting array

Java Code

Run
import java.util.*;
public
class Main {
    public
    static void shift(int[] arr) {
        int j = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] < 0) {
                if (i != j) swap(arr, i, j);
                j++;
            }
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
    // used for swapping ith and jth elements of array
    public
    static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
    public
    static void main(String[] args) throws Exception {
        

        int[] arr = new int[]{ -1,0,3,1,-4}; 
       
        shift(arr);
    }
}

Output :

-1 -2 4 2 2