C++ 1D Array Program | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 3

C++ 1D Array Program

Write a Function to shift all the negative numbers in a one dimensional array to the left without affecting the order of other elements.

4th Aug 2017, 4:48 AM
Rohit Singh Rawat
Rohit Singh Rawat - avatar
5 Answers
0
start from the right of the array and move every positive element past the negative ones: void func(int *arr, int n) { int i, j, tmp; for(i = n-2; i >= 0; --i) { if(arr[i] >= 0 && arr[i+1] < 0) { tmp = arr[i]; for(j = i+1; arr[j] <= 0 && j < n; ++j) arr[j-1] = arr[j]; arr[j-1] = tmp; } } }
4th Aug 2017, 5:16 AM
lion
lion - avatar
0
I just realized it doesn't matter where you start (I had that sleepy first idea where if you start from the left, you have to move the whole array with every number you had to shift, but in this case it wasn't the case), so here is the modified code to actually move the negative numbers to the left, not the positives to the right (it's the same thing - same result, same time complexity - but feels more like doing what was asked rather than a workaround). https://code.sololearn.com/cpiT3eaUYS84/?ref=app
4th Aug 2017, 6:32 AM
lion
lion - avatar
0
great work... i am thankful...
4th Aug 2017, 6:35 AM
Rohit Singh Rawat
Rohit Singh Rawat - avatar
- 1
thanks lion... i will catch back for queries...
4th Aug 2017, 5:18 AM
Rohit Singh Rawat
Rohit Singh Rawat - avatar
- 1
ok thanks
4th Aug 2017, 5:43 AM
Rohit Singh Rawat
Rohit Singh Rawat - avatar