Reposting here, as the question where I replied got closed (duplicate of this one).
I'm sorry about answering this using Python, but it is an exercise I wanted to do. The code is meant to be verbose, to output the steps of the algorithm. Of course, the translation to C is not difficult, as long as you are careful moving the pointer. Cheers!
# Put zeros on the left, ones on the right in one pass
a = [1,0,1,0,0,1,1,1,0,0,1,0,0,1,0,0,1,1,0,0,1,1,0,0,1,0,1]
cl = 0
cr = len(a) - 1
print a
while(True):
if cl + 1 == cr:
print 'last pass; adjacent elements'
if a[cl] == 0:
print 'a[%d] = 0; leave and exit loop' % (cl)
print 'final array:'
print a
break
if a[cl] == 1:
print 'a[%d] = 1; try to swap with a[%d]' % (cl, cr)
if a[cr] == 1:
print 'a[%d] = 1 as well; leave and exit loop' % (cr)
print 'final array:'
print a
break
else:
print 'a[%d] and a[%d] swapped; leave and exit loop' % (cl, cr)
a[cl] = 0
a[cr] = 1
print 'final array:'
print a
break
if a[cl] == 0:
print 'a[%d] = 0; leave and move on to a[%d]' % (cl,cl+1)
cl += 1
continue
else:
print 'a[%d] = 1 move to the right' % (cl)
while(True):
if a[cr] == 1:
print 'a[%d] cannot be moved to a[%d], try a[%d]' % (cl, cr, cr-1)
cr -= 1
continue
else:
print 'a[%d] swapped with a[%d]' % (cl, cr)
a[cr] = 1
a[cl] = 0
cr -= 1
cl += 1
print 'next up: a[%d]; right side blocked up to %d' % (cl,cr)
break
if (cl + 1) == cr:
break
Sample output:
[1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1]
a[0] = 1 move to the right
a[0] cannot be moved to a[26], try a[25]
a[0] swapped with a[25]
next up: a[1]; right side blocked up to 24
a[1] = 0; leave and move on to a[2]
a[2] = 1 move to the right
a[2] cannot be moved to a[24], try a[23]
a[2] swapped with a[23]
next up: a[3]; right side blocked up to 22
a[3] = 0; leave and move on to a[4]
a[4] = 0; leave and move on to a[5]
a[5] = 1 move to the right
a[5] swapped with a[22]
next up: a[6]; right side blocked up to 21
a[6] = 1 move to the right
a[6] cannot be moved to a[21], try a[20]
a[6] cannot be moved to a[20], try a[19]
a[6] swapped with a[19]
next up: a[7]; right side blocked up to 18
a[7] = 1 move to the right
a[7] swapped with a[18]
next up: a[8]; right side blocked up to 17
a[8] = 0; leave and move on to a[9]
a[9] = 0; leave and move on to a[10]
a[10] = 1 move to the right
a[10] cannot be moved to a[17], try a[16]
a[10] cannot be moved to a[16], try a[15]
a[10] swapped with a[15]
next up: a[11]; right side blocked up to 14
a[11] = 0; leave and move on to a[12]
a[12] = 0; leave and move on to a[13]
last pass; adjacent elements
a[13] = 1; try to swap with a[14]
a[13] and a[14] swapped; leave and exit loop
final array:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]