Actually it is not that hard to solve if you allow for a few errors in the process. You should always pack square textures on area size, once you have that sorted list fit the biggest one into the texture and split it the original texture on the inserted textures biggest dimension. Now check if the next texture fit into the biggest square that doesn't hold a texture yet. If it doesn't output an error and increase the atlas texture size and start again. If it does sub divide that square again as before and continue with the next square. Here is the source article I used when I had to implement this for a game. Remember ordering on area size is important to get an efficient subdivision of the texture.
"But i have some problems here,if every textures have a different size,what should i do?" - Packing different sized textures optimally is a very hard problem, it's a variant of the bin packing problem and is basically unsolvable. There are simple algorithms which produce good results, but you might be best using an existing packing tool rather than write your own.
This problem gets harder when you have to pack a texture with the atlas for a model and flattened out geometry although the same process should work as well, you might need a different form than a square to sub divide on though.