Tuesday, 3 May 2022

Rearrange the numbers

 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

Switch case in Java

 Problem statement: Return the capital of a state based on input state          public String getCapital(String state){               switch...