w3resource

Java: Arrange the elements of a given array of integers where all positive integers appear before all the negative integers


49. Arrange array with positive integers before negatives

Write a Java program to arrange the elements of an array of integers so that all positive integers appear before all negative integers.

Pictorial Presentation:

Java Array Exercises: Arrange the elements of a given array of integers where all positive  integers appear before all the negative integers


Sample Solution:

Java Code:

// Import the necessary Java utility class for working with arrays.
import java.util.Arrays;

// Define the Main class.
public class Main {

    // The main method for executing the program.
    public static void main(String[] args) {
        // Define an array of integers.
        int arra_nums[] = {-4, 8, 6, -5, 6, -2, 1, 2, 3, -11};
        
        // Print the original array.
        System.out.println("Original array: " + Arrays.toString(arra_nums)); 
        
        int j, temp, arr_size;

        // Get the size of the array.
        arr_size = arra_nums.length;

        for (int i = 0; i < arr_size; i++) {
            j = i;  
            
            // Shift positive numbers to the left and negative numbers to the right.
            while ((j > 0) && (arra_nums[j] > 0) && (arra_nums[j - 1] < 0)) {
                temp = arra_nums[j];
                arra_nums[j] = arra_nums[j - 1];
                arra_nums[j - 1] = temp;
                j--;
            }
        }

        // Print the modified array.
        System.out.println("New array: " + Arrays.toString(arra_nums)); 
    }       
}

Sample Output:

Original array : [-4, 8, 6, -5, 6, -2, 1, 2, 3, -11]
New array : [8, 6, 6, 1, 2, 3, -4, -5, -2, -11]

Flowchart:

Flowchart: Arrange the elements of a given array of integers where all positive integers appear before all the negative integers


For more Practice: Solve these Related Problems:

  • Write a Java program to partition an array into three parts: negative numbers, zeros, and positive numbers.
  • Write a Java program to sort an array of integers such that all even numbers appear before odd numbers, maintaining relative order.
  • Write a Java program to rearrange an array such that the largest and smallest elements alternate.
  • Write a Java program to split an array into two parts, one containing numbers greater than a given value and another containing numbers less than it.

Go to:


PREV : Arrange array with negative integers before positives.
NEXT : Sort array with alternate max-min values.

Java Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.