package com.kkjavatutorials.client;
/**
* @author KK JavaTutorials
* Write a program to move all negative elements to end in an int array
* without using existing data structures
*/
public class MoveNegativeArrayElementsAtLast_1 {
public static void main(String[] args) {
//input Array
int arr[] = {3, -3, 45, 2, -19, -7, 56, 45 };
int n = arr.length;
moveAllNegativeElementsAtLastInArray(arr,n);
//Printing array after moving all negative elements in last
for (int i : arr) {
System.out.print(i+" ");
}
}
private static void moveAllNegativeElementsAtLastInArray(int[] arr, int n) {
//Creating temporary array with same size as input array
int tempAll[] = new int[n];
//Start index of tempAll[] array
int j =0;
//Storing positive or zero elements in tempAll[] array
for (int i = 0; i < arr.length; i++) {
if(arr[i]>=0) {
tempAll[j++] = arr[i];
}
}
//If all numbers are either positive or zeros
if(j == n || j == 0)
return;
//Storing negative elements in tempAll[] array
for (int i = 0; i < arr.length; i++) {
if(arr[i] < 0) {
tempAll[j++] = arr[i];
}
}
//Copy all elements from tempAll[] to arr[] array
for (int i = 0; i < tempAll.length; i++) {
arr[i] = tempAll[i];
}
}
}