|
| 1 | +//This program will move all negative elements of an array of integers to the end of the array without changing the order of positive element and negative element |
| 2 | + |
| 3 | +#include <iostream> |
| 4 | +using namespace std; |
| 5 | + |
| 6 | +void segregateElements(int nums[], int n) |
| 7 | +{ |
| 8 | + // Array to store result |
| 9 | + int result[n]; |
| 10 | + |
| 11 | + int j = 0; // index of result |
| 12 | + for (int i = 0; i < n ; i++) |
| 13 | + if (nums[i] >= 0 ) |
| 14 | + result[j++] = nums[i]; |
| 15 | + if (j == n || j == 0) |
| 16 | + return; |
| 17 | + |
| 18 | + for (int i = 0 ; i < n ; i++) |
| 19 | + if (nums[i] < 0) |
| 20 | + result[j++] = nums[i]; |
| 21 | + |
| 22 | + // Copy contents to nums[] |
| 23 | + memcpy(nums, result, sizeof(result)); |
| 24 | +} |
| 25 | + |
| 26 | +int main() |
| 27 | +{ |
| 28 | + int nums[] = {1, 3, -7, 2, -13, 19, -20}; |
| 29 | + int n = sizeof(nums)/sizeof(nums[0]); |
| 30 | + cout << "Original array: "; |
| 31 | + for (int i=0; i < n; i++) |
| 32 | + cout << nums[i] <<" "; |
| 33 | + segregateElements(nums, n); |
| 34 | + |
| 35 | + printf("\nArray elements after rearrange: "); |
| 36 | + for (int i=0; i < n; i++) |
| 37 | + cout << nums[i] <<" "; |
| 38 | + return 0; |
| 39 | + |
| 40 | +} |
0 commit comments