verify this part of code.

should be:
if (id1 > id2) {
  int swap = id1;
  id1 = id2;
  id2 = swap;
}