; Return in the EAX register the index of the word in RDI in the signed word ; array sorted in ascending order starting at the address in RSI and having RDX ; members, or -1 if not found. ;int binarySearch(int t, int *x, unsigned n). /* From the book "Programming */ ;{ /* Pearls" by John Louis Bentley (n, */ ; unsigned l = 0, u = n - 1, m; /* l, u and m are of type int there) */ ; while (l <= u) { ; m = (l + u) / 2; /* Danger of overflow (JDK-5045582)! */ ; if (x[m] < t) ; l = m + 1; ; else if (x[m] == t) ; return m; ; else /* x[m] > t */ ; u = m - 1; ; } ; return -1; ;} ; Word searched for t is RDI, array x is RSI, size n is RDX by definition; ; lower index l is RCX, upper index u is RDX, middle index m is RAX (by choice). option prologue:none, epilogue:none .code binsrch proc _binsrch proc .for (RCX = 0, RDX--: RCX <= RDX: ) LEA RAX,[RDX+RCX]; m = (l + u) SHR RAX,1 ; / 2; // unsigned CMP [RSI+8*RAX],RDI .break .if (equal?); if (x[m] == t) return m; .if (less?) ; if (x[m] < t) LEA RCX,[RAX+1]; l = m + 1; .else ; else /* x[m] > t */ LEA RDX,[RAX-1]; u = m - 1; .endif .endfor .if (!equal?) MOV RAX,-1 ; return -1; .endif RET _binsrch endp binsrch endp end