Java Online Compiler
Example: Rearrange Positive and Negative Numbers in an Array in Java language
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Rearrange Positive and Negative Numbers in an Array in Java language import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int[] arru = {-34, 38, -35, -36, 35, 49, 47, 41, -41, -41, 49}; int arru_size = arru.length; // It's the array iteration System.out.print("------This is the given array before arrangement------\n\t"); for (int i = 0; i<arru_size; i++) { System.out.print(arru[i] + ",\t"); } System.out.print("\n\n"); // It's the array iteration System.out.print("------This is the Re-arranged array------\n\t"); // This will re-arrange the given array reArrangeNumbers(arru, 10); for (int i = 0; i<11; i++) { System.out.print(arru[i] + ",\t"); } System.out.print("\n"); } public static void alterNumber(int[] arru, int i, int j) { int temp = arru[i]; arru[i] = arru[j]; arru[j] = temp; } public static void splitNegativeElement(int[] arru, int size) { int temp, left = 0, right = size - 1; while (right > left) { while (arru[left]<0) left++; while (arru[right] > 0) right--; if (left<right) { alterNumber(arru, left, right); } } } // It's the driver function of // array element arrangements public static void reArrangeNumbers(int[] arru, int size) { int i, j; splitNegativeElement(arru, size); for (i = 0; arru[i]<0; i++); for (j = 1; (j<i) && (arru[j]<0); j += 2) { alterNumber(arru, i, j); i++; } return; } }
Output
Clear
ADVERTISEMENTS