- 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.
5 Respuestas
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;
}
}
}
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
0
great work... i am thankful...
- 1
thanks lion... i will catch back for queries...
- 1
ok thanks