Segregate Positive followed by Negative Elements in an Array

Introduction

This example will show you how to segregate positive followed by negative elements in an Array using Java programming language. The elements are integer values here. The function will put all positive numbers first, and then negative numbers and finally count the number of moves required to arrange all elements in the desired order.

Prerequisite

Knowledge of Java

Segregate Positive followed by Negative

Let’s move on to the example implementation…

Suppose you have an array of elements as -13, 10, 21, -20, 52, -8, 4, -7, -2. Now you need to find out minimum moves to segregate positive followed by negative elements in Array so that all positive elements will be in the front of the array and all negative elements will be in the back of the array.

So the resulting array will 52 10 21 4 -13 -8 -20 -7 -2.

It’s simply you need to swap element -13 with element 52 and -20 with 4 in the array.

So you need only two moves for our example to segregate the positive followed by negative elements in an array.

public class SegregatePositiveAndNegativeArrayElements {
	public static void main(String[] args) {
		int[] arr = new int[] { -13, 10, 21, -20, 52, -8, 4, -7, -2 };
		int minMoves = minMovesToEvenFollowedByOdd(arr);
		System.out.println("Minimum moves to segregate positive followed by negative elements: " + minMoves);
	}
	static int minMovesToEvenFollowedByOdd(int[] arr) {
		int moves = 0;
		int totalLength = arr.length;
		for (int i = 0; i < totalLength / 2; i++) {
			if (arr[i] < 0) {
				for (int j = totalLength / 2; j < totalLength; j++) {
					if (arr[j] > 0) {
						int temp = arr[i];
						arr[i] = arr[j];
						arr[j] = temp;
						moves++;
						break;
					} else {
						continue;
					}
				}
			} else {
				continue;
			}
		}
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + " ");
		}
		System.out.println();
		return moves;
	}
}

Testing the Application

Now run the above code, you should see below output:

52 10 21 4 -13 -8 -20 -7 -2
Minimum moves to segregate positive followed by negative elements: 2

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *