Positive elements at even and negative at odd positions ( Relative order not maintained ) | Java program to rearrange positive and negative numbers ; Move forward the positive pointer till negative number number not encountered ; Move forward the negative pointer till positive number number not encountered ; Swap array elements to fix their position . ; Break from the while loop when any index exceeds the size of the array ; Driver code
import java . io . * ; class GFG { static void rearrange ( int a [ ] , int size ) { int positive = 0 , negative = 1 , temp ; while ( true ) { while ( positive < size && a [ positive ] >= 0 ) positive += 2 ; while ( negative < size && a [ negative ] <= 0 ) negative += 2 ; if ( positive < size && negative < size ) { temp = a [ positive ] ; a [ positive ] = a [ negative ] ; a [ negative ] = temp ; } else break ; } } public static void main ( String args [ ] ) { int arr [ ] = { 1 , - 3 , 5 , 6 , - 3 , 6 , 7 , - 4 , 9 , 10 } ; int n = arr . length ; rearrange ( arr , n ) ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } }