Skip to content

Commit 0bd8ff9

Browse files
authored
Merge pull request #924 from MannyP31/manny
Cpp program to shuffle negative numbers to the end of the array.
2 parents 29c17bf + ead99fd commit 0bd8ff9

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Arrays/negative_number_shuffle.cpp

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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

Comments
 (0)