I've recently become interested in programming physics simulations and played around with elastic collisions of balls using java.  A natural extension of this for me was to add gravity and see how the coding for collisions between pairs of balls works with larger numbers of balls.  In particular, I was hoping to get a simulation in which I could throw a bunch of balls together and have them stack up on the ground in a realistic manner.

I have an applet online with what I have so far at:

As you can see for yourself by adding enough balls to fill a significant portion of the virtual room (with gravity on), the stacking of balls works to some extent.  But balls eventually get pushed together and stuck overlapping and frozen in space for a while, which is obviously a problem.  My question is if you have any ideas for a good way to implement the collisions of multiple balls during the course of one frame of motion.

The way I handle it right now is just cycling through each pair of balls once per frame to see if each pair collides. If a pair is found to collide, I move the two balls to where they are located the instant before they collide (ie 1 pixel separation) and change the speeds accordingly for the elastic collision of equal masses. In subsequent checks for collisions, I use the new ball speeds and positions. So if a ball collides multiple times in a cycle, it'll end up in the last place it collided, which may very well be overlapping with another ball.

I've experimented with also moving the ball after colliding according to new velocities, which just makes the overlapping problem much worse. I've also tried looping the collision cycle in each frame to run as long as there are still two balls colliding, but then it gets stuck in infinite loops when balls just don't become separated.

I also have one last side question. Right now collisions between two balls are completely elastic, and collisions between a ball and a wall have a coefficient of restitution of 0.8. How would I go about making the balls lose energy when colliding with each other so that they don't constantly bounce around like they're undergoing Brownian motion? Can I just multiply their speeds after collision by a similar coefficient of restitution, or will the directions change because of this? (I tried using a restitution coefficient, which has an annoying effect of making balls get stuck together earlier and frozen in space instead of rolling off each other.)

That's all I have for now, thanks for any suggestions you have!