Sorting zeros in an array

Hi ! I'm having trouble getting good results here. I'm trying to write a function that sorts arrays in the following way:

1 - The first element has to be '0' (This is already guaranteed earlier from how i fill the array. I just don't want this element to change)
2 - Any other '0' encountered is to be moved to the end of the array and all elements shifted by 1 to the left.

Examples:

myArray[7] = {0, 1, 3, 0, 2, 4, 5} is sorted to {0, 1, 3, 2, 4, 5, 0}
and myArray[7] = {0, 0, 3, 0, 2, 4, 5} is sorted to {0, 3, 2, 4, 5, 0, 0}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
myArray[7] = {0, 1, 3, 0, 2, 4, 5};

int zeroCounter = 0;

for(int i=1; i<(6-zeroCounter); i++)
{				
	if (myArray[i] == 0)
	{			   
		for(int j=i; j<(6-zeroCounter); j++)
		{
			myArray[j] = myArray[j+1];
		}				 			 
		zeroCounter += 1;
		myArray[7-zeroCounter] = 0;
	}
}


I would also like my 'zeroCounter' to count all zeros in the array (except for the 0 element in myArray[0] )
And what's the problem? Looks correct to me.
Edit: ah, not quite correct. After moving the elements, you need to adjust the index, otherwise you'll skip the next element.
Last edited on
Hmm I'm not sure if i see it...

Something like this ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
for(int i=1; i<(6-zeroCounter); i++)
{				
	if (myArray[i] == 0)
	{			   
		for(int j=i; j<(6-zeroCounter); j++)
		{
			myArray[j] = myArray[j+1];
		}				 			 
		zeroCounter += 1;
		myArray[7-zeroCounter] = 0;
               
                i -= 0;
	}
}
Last edited on
Say... what happens when you subtract 0 from a number?
hahaa oops i meant:

i -= 1;

Thanks Athar I think it works now :)
Last edited on
This could be done much simpler if you used C++:

1
2
int myArray[7] = {0, 1, 3, 0, 2, 4, 5};
std::stable_partition(myArray+1, myArray+7, std::bind2nd(std::not_equal_to<int>(), 0));


or, avoiding deprecated features,

1
2
int myArray[7] = {0, 1, 3, 0, 2, 4, 5};
std::stable_partition(myArray+1, myArray+7, [](int n){return n!=0;});


or even without any functors:

1
2
int myArray[7] = {0, 1, 3, 0, 2, 4, 5};
std::fill(std::remove(myArray+1, myArray+7, 0), myArray+7, 0);
Last edited on
I like Cubbi's answer, though if you use all-in-one solutions like this, best to add a comment so people know what the line is doing.

That said, if you are implementing this using loops, I might recommend an approach that maintains 2 pointers - one points at the last non-0 number, and the other the second 0 in the set. When you do a swap, you need to adjust both pointers. Your end condition would be when the pointers cross.
Topic archived. No new replies allowed.