Problem no 5 :Move all the negative elements to left side of the array.

QUESTION:
Move all negative numbers to beginning and positive to end with constant extra space
  • Difficulty Level :EASY
  •  

An array contains both positive and negative numbers in random order. Rearrange the array elements so that all negative numbers appear before all positive numbers.
Examples : 

Input: -12, 11, -13, -5, 6, -7, 5, -3, -6
Output: -12 -13 -5 -7 -3 -6 11 6 5


ANSWER:

                  void rearrange(int arr[],int n)
{
    int j=0;
    for(int i=0;i<n;i++)
    {
        if(arr[i]<0)
        {
            if(i!=j)
            {
                int temp=arr[i];
                arr[i]=arr[j];
                arr[j]=temp;
            }
            j++;
        }
    }
    for(int k=0;k<n;k++)
    {
        cout<<arr[k]<<" ";
    }
}

Comments

Popular posts from this blog

Problem no 18(array):count the number of pairs in array whose sum is equal to the given number.

convert the integer number to its binary representation.

Tcs assessment problem: museum problem.