﻿ Java: Add every +ve, -ve number to the right, left

# Java Exercises: Move every positive number to the right and every negative number to the left of a given array of integers

## Java Basic: Exercise-165 with Solution

Write a Java program to move every positive number to the right and every negative number to the left of a given array of integers.

Pictorial Presentation: Sample Solution:

Java Code:

``````import java.util.*;
public class Solution {
public static int[] split_sorting_array(int[] nums) {
if (nums == null) {
throw new IllegalArgumentException("Null array......!");
}
boolean flag = true;
while (flag) {
flag = false;
for (int j = 0; j < nums.length - 1; j++) {
if (nums[j] > nums[j + 1]) {
swap(nums, j, j + 1);
flag = true;
}
}
}
return nums;
}
private static void swap(int[] nums, int left, int right) {
int temp = nums[right];
nums[right] = nums[left];
nums[left] = temp;
}
public static void main(String[] args) {
int[] nums = {-2,3,4,-1,-3,1,2,-4,0};
System.out.println("\nOriginal array: " + Arrays.toString(nums));
int[] result = split_sorting_array(nums);
System.out.println("\nResult: " + Arrays.toString(result));
}
}
```
```

Sample Output:

```Original array: [-2, 3, 4, -1, -3, 1, 2, -4, 0]

Result: [-4, -3, -2, -1, 0, 1, 2, 3, 4]
```

Flowchart: Java Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿

## Java: Tips of the Day

How to remove leading zeros from alphanumeric text?

Regex is the best tool for the job; what it should be depends on the problem specification. The following removes leading zeroes, but leaves one if necessary (i.e. it wouldn't just turn "0" to a blank string).

```s.replaceFirst("^0+(?!\$)", "")
```

The ^ anchor will make sure that the 0+ being matched is at the beginning of the input. The (?!\$) negative lookahead ensures that not the entire string will be matched.

Test harness:

```String[] in = {
"01234",         // ""
"0001234a",      // "[1234a]"
"101234",        // ""
"000002829839",  // ""
"0",             // ""
"0000000",       // ""
"0000009",       // ""
"000000z",       // "[z]"
"000000.z",      // "[.z]"
};
for (String s : in) {
System.out.println("[" + s.replaceFirst("^0+(?!\$)", "") + "]");
}```

Ref: https://bit.ly/2Qdcl8a