Given an array of positive and negative numbers, arrange them such that all negative integers appear before all the positive integers in the array without using any additional data structure like hash table, arrays, etc. The order of appearance should be maintained.
Examples:
Input: [12 11 -13 -5 6 -7 5 -3 -6]
Output: [-13 -5 -7 -3 -6 12 11 6 5]
#include <stdio.h>
void printArray( int arr[], int n)
{
for ( int i = 0; i < n; i++)
printf ( "%d " , arr[i]);
printf ( "\n" );
}
void RearrangePosNeg( int arr[], int n)
{
int key, j;
for ( int i = 1; i < n; i++) {
key = arr[i];
if (key > 0)
continue ;
j = i - 1;
while (j >= 0 && arr[j] > 0) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
int main()
{
int arr[] = { -12, 11, -13, -5, 6, -7, 5, -3, -6 };
int n = sizeof (arr) / sizeof (arr[0]);
RearrangePosNeg(arr, n);
printArray(arr, n);
return 0;
}
|
Output:
-12 -13 -5 -7 -3 -6 11 6 5
Output:
-12 -13 -5 -7 -3 -6 11 6 5
import java.io.*;
class GFG {
static void printArray( int arr[], int n)
{
for ( int i = 0 ; i < n; i++)
System.out.print(arr[i] + " " );
System.out.println();
}
static void RearrangePosNeg( int arr[], int n)
{
int key, j;
for ( int i = 1 ; i < n; i++) {
key = arr[i];
if (key > 0 )
continue ;
j = i - 1 ;
while (j >= 0 && arr[j] > 0 ) {
arr[j + 1 ] = arr[j];
j = j - 1 ;
}
arr[j + 1 ] = key;
}
}
public static void main(String[] args)
{
int arr[] = { - 12 , 11 , - 13 , - 5 , 6 , - 7 , 5 , - 3 , - 6 };
int n = arr.length;
RearrangePosNeg(arr, n);
printArray(arr, n);
}
}
|
Output:
-12 -13 -5 -7 -3 -6 11 6 5
Output:
-12 -13 -5 -7 -3 -6 11 6 5
Time complexity of above solution is O(n2) and auxiliary space is O(1). We have maintained the order of appearance and have not used any other data structure.
def printArray(arr, n):
for i in range (n):
print (arr[i], end = " " )
print ()
def RearrangePosNeg(arr, n):
for i in range ( 1 , n):
key = arr[i]
if (key > 0 ):
continue
j = i - 1
while (j > = 0 and arr[j] > 0 ):
arr[j + 1 ] = arr[j]
j = j - 1
arr[j + 1 ] = key
if __name__ = = "__main__" :
arr = [ - 12 , 11 , - 13 , - 5 ,
6 , - 7 , 5 , - 3 , - 6 ]
n = len (arr)
RearrangePosNeg(arr, n)
printArray(arr, n)
|
Output:
-12 -13 -5 -7 -3 -6 11 6 5
Output:
-12 -13 -5 -7 -3 -6 11 6 5
Comments
Post a Comment