Move all negative elements to end in order with extra space allowed | Java program to Move All - ve Element At End Without changing order Of Array Element ; Moves all - ve element to end of array in same order . ; Create an empty array to store result ; Traversal array and store + ve element in temp array index of temp ; If array contains all positive or all negative . ; Store - ve element in temp array ; Copy contents of temp [ ] to arr [ ] ; Driver code
import java . util . Arrays ; class GFG { static void segregateElements ( int arr [ ] , int n ) { int temp [ ] = new int [ n ] ; int j = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] >= 0 ) temp [ j ++ ] = arr [ i ] ; if ( j == n j == 0 ) return ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] < 0 ) temp [ j ++ ] = arr [ i ] ; for ( int i = 0 ; i < n ; i ++ ) arr [ i ] = temp [ i ] ; } public static void main ( String arg [ ] ) { int arr [ ] = { 1 , - 1 , - 3 , - 2 , 7 , 5 , 11 , 6 } ; int n = arr . length ; segregateElements ( arr , n ) ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } }