I want to know an exact algorithm (or near that) behind \'git merge\'. The answers at least to these sub-questions will be helpful:
Here is the original implementation
http://git.kaarsemaker.net/git/blob/857f26d2f41e16170e48076758d974820af685ff/git-merge-recursive.py
Basically you create a list of common ancestors for two commits and then recursively merge them, either fast forwarding them, or creating virtual commits that get used for the basis of a three-way merge on the files.