Explore
ProGrad Programs
About Us

Edit
Reply




Edit

Rearrange positive and negative numbers in an array | FACE Prep

Published on 09 Mar 2020

The problem to rearrange positive and negative numbers in an array can be done in 2 different methods. They are


Method 1: This approach moves all negative numbers to the beginning and positive numbers to the end but changes the order of appearance of the elements of the array.


Method 2: In this approach, we separate the negative and positive numbers of the array by maintaining the order of appearance of elements of the array.


Method 1 to rearrange positive and negative numbers in an array


In this approach, the order of appearance of the elements of the array is not maintained. Start traversing the array and if a negative element is encountered, swap the negative element and first positive element and continue until all the elements have been traversed.


Algorithm


  1. Declare an array and input the array elements.
  2. Start traversing the array and if the current element is negative,swap the current element with the first positive element and continue traversing until all the elements have been encountered.
  3. Print the rearranged array.


Test case:


  • Input: 1 -1 2 2 3 -3
  • Output: -1 -2 -3 1 3 2


C
C++

Output
Input- Enter the number of elements:6 Input the array elements:-1 1 -2 2 -3 3 Original array:-1 1 -2 2 -3 3 Output- Rearranged array : -1 -2 -3 2 1 3


Method 2 to rearrange positive and negative numbers in an array


In this approach, the order of appearance of the elements of the array is maintained. Start traversing the array and if a positive element is encountered, continue traversing. If a negative element is encountered, shift all the positive numbers to the right by one position and insert the negative number in the sequence array[0 to n-1].


Algorithm


  1. Declare an array and input the array elements.
  2. Start traversing the array and if the current element is positive, traverse to the next element in the array.
  3. If the current element is negative, right shift the positive elements by one position and insert the negative number in the sequence array[0 to n-1].
  4. Print the rearranged array.


Test case:


  • Input: 1 -1 2 -2 3 -3
  • Output: -1 -2 -3 1 2 3




C
C++

Output
Input- Enter the number of elements:6 Input the array elements:-1 1 -2 2 -3 3 Original array:-1 1 -2 2 -3 3 Output- Rearranged array : -1 -2 -3 1 2 3


Recommended Programs






If you have any feedback about this article and want to improve this, please write to enquiry@faceprep.in