Who holds the copyright if I did research at one university and write a thesis at another?
You confuse two different things: The copyright attaches to the written work (in your case the thesis). The intellectual property attaches to the content of the contribution (in your case, the algorithm).

Likely (though I'm not qualified to give legal advice), the copyright for your thesis resides with you and/or university B, whereas the intellectual property in the algorithm resides with university A.