Alternate positive and negative numbers

Given an unsorted array Arr of N positive and negative numbers. Your task is to create an array of alternate positive and negative numbers without changing the relative order of positive and negative numbers.
Note: Array should start with positive number.

 

Example 1:

Input: 
N = 9
Arr[] = {9, 4, -2, -1, 5, 0, -5, -3, 2}
Output:
9 -2 4 -1 5 -5 0 -3 2

Example 2:

Input: 
N = 10
Arr[] = {-5, -2, 5, 2, 4, 7, 1, 8, 0, -8}
Output:
5 -5 2 -2 4 -8 7 1 8 0 



method:

store the array elements positive and negative separately. Then combine them accoring to the condition.

c++ implementation:

	void rearrange(int arr[], int n) 
	{
	    int b[n];int c[n];int x=0; int y=0;
	    for(int i=0;i<n;i++)
	    {
	        if(arr[i]<0)
	        {
	            b[x]=arr[i];
	            x++;
	        }
	        else
	        {
	            c[y]=arr[i];
	            y++;
	        }
	    }
	    
	    int u=0;int v=0;int f=0;int i=0;
	    while(u<x && v<y)
	    {
	        if(f==1)
	        {
	            arr[i]=b[u];
	            u++;
	        }
	        else
	        {
	            arr[i]=c[v];
	            v++;
	        }
	        f=!f;
	        i++;
	    }
	    
	    while(u<x)
	    {
	        arr[i]=b[u];
	        u++;
	        i++;
	    }
	    
	     while(v<y)
	    {
	        arr[i]=c[v];
	        v++;
	        i++;
	    }
	}

above one is using arrays

(or )  //both are same

below one is using vectors

	   void rearrange(int arr[], int n) 
	   {
	    vector<int> n, p;
	    for (int i = 0; i < n; i++) {

	        if (arr[i] < 0)
	            n.push_back(arr[i]);
	        else
	           p.push_back(arr[i]);
	    }

	    int i = 0, j = 0, k = 0;
	    while (i < n.size() && j < p.size()) {
	        arr[k++] = p[j++];
	        arr[k++] = n[i++];
	    }
	    while (j < p.size()) { arr[k++] = p[j++]; }

	    while (i < n.size()) { arr[k++] = n[i++]; }
	   }
Time Complexity: O(n) 
space Complexity: O(n) 





No comments

darkmode