Given an unsorted array arr[] of both negative and positive integer. The task is place all negative element at the end of array without changing the order of positive element and negative element.
Examples:
Input : arr[] = {1, -1, 3, 2, -7, -5, 11, 6 }
Output : 1 3 2 11 6 -1 -7 -5
Input : arr[] = {-5, 7, -3, -4, 9, 10, -1, 11}
Output : 7 9 10 11 -5 -3 -4 -1
We have discussed different approaches to this problem in below post.
Rearrange positive and negative numbers with constant extra space
The problem becomes easier if we are allowed to use extra space. Idea is create an empty array (temp[]). First we store all positive element of given array and then we store all negative element of array in Temp[]. Finally we copy temp[] to original array.
Implementation:
// C++ program to Move All -ve Element At End // Without changing order Of Array Element #include<bits/stdc++.h> using namespace std;
// Moves all -ve element to end of array in // same order. void segregateElements( int arr[], int n)
{ // Create an empty array to store result
int temp[n];
// Traversal array and store +ve element in
// temp array
int j = 0; // index of temp
for ( int i = 0; i < n ; i++)
if (arr[i] >= 0 )
temp[j++] = arr[i];
// If array contains all positive or all negative.
if (j == n || j == 0)
return ;
// Store -ve element in temp array
for ( int i = 0 ; i < n ; i++)
if (arr[i] < 0)
temp[j++] = arr[i];
// Copy contents of temp[] to arr[]
memcpy (arr, temp, sizeof (temp));
} // Driver program int main()
{ int arr[] = {1 ,-1 ,-3 , -2, 7, 5, 11, 6 };
int n = sizeof (arr)/ sizeof (arr[0]);
segregateElements(arr, n);
for ( int i = 0; i < n; i++)
cout << arr[i] << " " ;
return 0;
} |
// Java program to Move All -ve Element At End // Without changing order Of Array Element import java.util.Arrays;
class GFG {
// Moves all -ve element to end of array in
// same order.
static void segregateElements( int arr[], int n)
{
// Create an empty array to store result
int temp[] = new int [n];
// Traversal array and store +ve element in
// temp array
int j = 0 ; // index of temp
for ( int i = 0 ; i < n; i++)
if (arr[i] >= 0 )
temp[j++] = arr[i];
// If array contains all positive or all
// negative.
if (j == n || j == 0 )
return ;
// Store -ve element in temp array
for ( int i = 0 ; i < n; i++)
if (arr[i] < 0 )
temp[j++] = arr[i];
// Copy contents of temp[] to arr[]
for ( int i = 0 ; i < n; i++)
arr[i] = temp[i];
}
// Driver code
public static void main(String arg[])
{
int arr[] = { 1 , - 1 , - 3 , - 2 , 7 , 5 , 11 , 6 };
int n = arr.length;
segregateElements(arr, n);
for ( int i = 0 ; i < n; i++)
System.out.print(arr[i] + " " );
}
} // This code is contributed by Anant Agarwal. |
# Python program to Move All -ve Element At End # Without changing order Of Array Element # Moves all -ve element to end of array in # same order. def move(arr,n):
j = 0
ans = [ None ] * n
i = 0 ;j = n - 1
for k in range (n):
if arr[k]> = 0 :
ans[i] = arr[k]
i + = 1
else :
ans[j] = arr[k]
j - = 1
ans[i:] = ans[n - 1 :i - 1 : - 1 ]
return ans
# Driver program arr = [ 1 , - 1 , - 3 , - 2 , 7 , 5 , 11 , 6 ]
n = len (arr)
print (move(arr, n))
# Contributed by Venkatesh hegde |
// C# program to Move All -ve Element At End // Without changing order Of Array Element using System;
class GFG {
// Moves all -ve element to
// end of array in same order.
static void segregateElements( int [] arr, int n)
{
// Create an empty array to store result
int [] temp = new int [n];
// Traversal array and store +ve element in
// temp array
int j = 0; // index of temp
for ( int i = 0; i < n; i++)
if (arr[i] >= 0)
temp[j++] = arr[i];
// If array contains all positive or all
// negative.
if (j == n || j == 0)
return ;
// Store -ve element in temp array
for ( int i = 0; i < n; i++)
if (arr[i] < 0)
temp[j++] = arr[i];
// Copy contents of temp[] to arr[]
for ( int i = 0; i < n; i++)
arr[i] = temp[i];
}
// Driver code
public static void Main()
{
int [] arr = { 1, -1, -3, -2, 7, 5, 11, 6 };
int n = arr.Length;
segregateElements(arr, n);
for ( int i = 0; i < n; i++)
Console.Write(arr[i] + " " );
}
} // This Code is contributed by vt_m. |
<script> // Javascript program to Move All -ve Element At End // Without changing order Of Array Element // Moves all -ve element to end of array in // same order. function segregateElements(arr, n)
{ // Create an empty array to store result
let temp= new Array(n);
// Traversal array and store +ve element in
// temp array
let j = 0; // index of temp
for (let i = 0; i < n ; i++)
if (arr[i] >= 0 )
temp[j++] = arr[i];
// If array contains all positive or all negative.
if (j == n || j == 0)
return ;
// Store -ve element in temp array
for (let i = 0 ; i < n ; i++)
if (arr[i] < 0)
temp[j++] = arr[i];
for (let i = 0; i < n ; i++) arr[i] = temp[i];
} // Driver program let arr= [1 ,-1 ,-3 , -2, 7, 5, 11, 6]; let n = arr.length; segregateElements(arr, n); for (let i = 0; i < n; i++)
document.write(arr[i] + " " );
</script> |
<?php // PHP program to Move All -ve Element At End // Without changing order Of Array Element // Moves all -ve element to end of // array in same order. function segregateElements(& $arr , $n )
{ // Create an empty array to store result
$temp = array (0, $n , NULL);
// Traversal array and store +ve
// element in temp array
$j = 0; // index of temp
for ( $i = 0; $i < $n ; $i ++)
if ( $arr [ $i ] >= 0 )
$temp [ $j ++] = $arr [ $i ];
// If array contains all positive
// or all negative.
if ( $j == $n || $j == 0)
return ;
// Store -ve element in temp array
for ( $i = 0 ; $i < $n ; $i ++)
if ( $arr [ $i ] < 0)
$temp [ $j ++] = $arr [ $i ];
// Copy contents of temp[] to arr[]
for ( $i = 0; $i < $n ; $i ++)
$arr [ $i ] = $temp [ $i ];
} // Driver Code $arr = array (1 ,-1 ,-3 , -2, 7, 5, 11, 6 );
$n = sizeof( $arr );
segregateElements( $arr , $n );
for ( $i = 0; $i < $n ; $i ++)
echo $arr [ $i ] . " " ;
// This code is contributed // by ChitraNayal ?> |
1 7 5 11 6 -1 -3 -2
Time Complexity : O(n)
Auxiliary space : O(n), since n extra space has been taken.
Another Approach: Using Stack
- Declare two stacks (pos, neg) which stores the positive and negative values of arr[i] respectively.
- Iterate over the arr from index 0 to n-1.
- If arr[i]<0, push the element in the neg stack.
- Else push the element in the pos stack.
- After traversing the array, use while loop until the neg stack becomes empty.
- Starting from the last of the index of the arr, store the top of the neg stack in arr and pop the element from the neg stack.
- When the neg stack become empty, store the top value of the pos stack and pop them until it becomes empty.
Below is the implementation of the above approach:
//C++ program to move all the negative elements at the right end #include <bits/stdc++.h> using namespace std;
//function to move all the negative elements to the end of the array //in the same order void moveNegElement( int arr[], int n){
stack< int > neg, pos;
for ( int i=0;i<n;i++){
if (arr[i]<0){
neg.push(arr[i]);
}
else {
pos.push(arr[i]);
}
}
//start from the last index
int i=n-1;
//pop the negative elements from the stack
//and store them in the array
while (!neg.empty()){
arr[i--]=neg.top();
neg.pop();
}
//after storing all the elements at the right end
//store the positive elements
while (!pos.empty()){
arr[i--]=pos.top();
pos.pop();
}
} // Driver program int main()
{ int arr[] = {1 ,-1 ,-3 , -2, 7, 5, 11, 6 };
int n = sizeof (arr)/ sizeof (arr[0]);
moveNegElement(arr, n);
for ( int i = 0; i < n; i++)
cout << arr[i] << " " ;
return 0;
} //this code is contributed by 525tamannacse1 |
import java.io.*;
import java.util.Stack;
public class GFG {
// Function to move all the negative elements to the end of
// the array in the same order
static void moveNegElement( int [] arr, int n) {
Stack<Integer> neg = new Stack<>();
Stack<Integer> pos = new Stack<>();
// Iterate through the array and separate negative and positive elements
for ( int i = 0 ; i < n; i++) {
if (arr[i] < 0 ) {
neg.push(arr[i]);
} else {
pos.push(arr[i]);
}
}
// Start from the last index
int i = n - 1 ;
// Pop the negative elements from the stack and
// store them in the array
while (!neg.isEmpty()) {
arr[i--] = neg.pop();
}
// After storing all the negative elements at the right end
// store the positive elements
while (!pos.isEmpty()) {
arr[i--] = pos.pop();
}
}
// Driver program
public static void main(String[] args) {
int [] arr = { 1 , - 1 , - 3 , - 2 , 7 , 5 , 11 , 6 };
int n = arr.length;
moveNegElement(arr, n);
for ( int i = 0 ; i < n; i++) {
System.out.print(arr[i] + " " );
}
}
} |
def move_neg_elements(arr, n):
neg = []
pos = []
# Separate negative and positive elements into two stacks
for i in range (n):
if arr[i] < 0 :
neg.append(arr[i])
else :
pos.append(arr[i])
# Start from the last index
i = n - 1
# Pop the negative elements from the stack and store them in the array
while neg:
arr[i] = neg.pop()
i - = 1
# After storing all the negative elements, store the positive elements
while pos:
arr[i] = pos.pop()
i - = 1
# Driver program if __name__ = = "__main__" :
arr = [ 1 , - 1 , - 3 , - 2 , 7 , 5 , 11 , 6 ]
n = len (arr)
move_neg_elements(arr, n)
for i in range (n):
print (arr[i], end = " " )
|
//C# program to move all the negative elements at the right end using System;
using System.Collections.Generic;
class Program
{ // Function to move all the negative elements to the end of the array
// in the same order
static void MoveNegElement( int [] arr)
{
Stack< int > neg = new Stack< int >();
Stack< int > pos = new Stack< int >();
foreach ( int element in arr)
{
if (element < 0)
{
neg.Push(element);
}
else
{
pos.Push(element);
}
}
// Start from the last index
int i = arr.Length - 1;
// Pop the negative elements from the stack
// and store them in the array
while (neg.Count > 0)
{
arr[i--] = neg.Pop();
}
// After storing all the elements at the right end,
// store the positive elements
while (pos.Count > 0)
{
arr[i--] = pos.Pop();
}
}
// Driver program
static void Main()
{
int [] arr = { 1, -1, -3, -2, 7, 5, 11, 6 };
MoveNegElement(arr);
foreach ( int element in arr)
{
Console.Write(element + " " );
}
Console.WriteLine();
}
} |
// Function to move all the negative elements to the end of the array // in the same order function moveNegElement(arr) {
const neg = [];
const pos = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] < 0) {
neg.push(arr[i]);
} else {
pos.push(arr[i]);
}
}
// Start from the last index
let i = arr.length - 1;
// Pop the negative elements from the stack
// and store them in the array
while (neg.length > 0) {
arr[i--] = neg.pop();
}
// After storing all the elements at the right end
// store the positive elements
while (pos.length > 0) {
arr[i--] = pos.pop();
}
} // Driver program const arr = [1, -1, -3, -2, 7, 5, 11, 6]; moveNegElement(arr); console.log(arr.join( " " ));
|
1 7 5 11 6 -1 -3 -2
Time Complexity: O(n), array traversed from 0 to n-1 in a single loop.
Space Complexity: O(n), used by the stack.
Related Articles:
Rearrange positive and negative numbers with constant extra space
Rearrange positive and negative numbers in O(n) time and O(1) extra space