Rearrange the numbers
Problem statement: We have an integer array {9,-5,7,0,-2,-1,8,-7} and rearrange this array by moving all positive numbers in left side and negative numbers in right side with numbers in given order
Sample input:
{9,-5,7,0,-2,-1,8,-7}
Output:
{9,7,0,8,-5,-2,-1,-7}
public void reArrangIntegerArray() {
int[] array = { 9, -5, 7, 0, -2, -1, 8, -7 };
for (int i = 0; i < array.length; i++) {
for (int j = 1; j < array.length; j++) {
if (array[j - 1] < 0
&& array[j] >= 0) {
int temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
}
}
}
for (int a : array) {
System.out.println(a);
}
}
Output:
{9,7,0,8,-5,-2,-1,-7}
No comments:
Post a Comment