Move all the negative elements to one side of the array

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.

Note: Order of elements is not important here.



//Here we have full program

1:  #include <bits/stdc++.h>  
2:  using namespace std;  
3:  void rearrange(int arr[], int n)  
4:  {  
5:       int j = 0;  
6:       for (int i = 0; i < n; i++) {  
7:            if (arr[i] < 0) {  
8:                 if (i != j)  
9:                      swap(arr[i], arr[j]);  
10:                 j++;  
11:            }  
12:       }  
13:  }  
14:  int main()  
15:  {  
16:       int n;  
17:      cin>>n;  
18:      int arr[n];  
19:      for(int i=0;i<n;i++)  
20:     {  
21:        cin>>arr[i];  
22:     }  
23:       rearrange(arr, n);  
24:      for (int i = 0; i < n; i++)  
25:    {            
26:       cout<<arr[i];  
27:    }  
28:       return 0;  
29:  }  

Post a Comment

0 Comments