Hello,

I have been given an assignment in which I am to write an assembly language version of the following binary search function & use a suitable main program written in C to test my function. The function in C in which I had to translate to assembly is:

```
int search(int a[], int low, int high, int value)
{
int mid;
if (low > high)
return -1;
mid = ( low + high) / 2;
if (a[mid] == value)
return mid;
else if (value < a[mid])
return search(a, low, mid - 1, value);
else
return search(a, mid + 1, high, value);
}
```

The assembly code which I wrote (Yes, I was hungry):

```
[SECTION .text]
global search
search: push EBP
mov EBP, ESP
add ESP, -4 ; Allocate mid at EBP - 4
lea EBX, [EBP + 4] ; Load "value" into EBX
lea ECX, [EBP + 8] ; Load "high" into ECX
lea EDI, [EBP + 12] ; Load "Low" into EDI
lea ESI, [EBP + 16] ; Load array *P into ESI
cmp EDI, ECX ; if (low>high)
jg poptarts ; jmp to return -1
jmp fishsticks ; Keep going
poptarts:
mov EAX, -1 ; return -1
jmp last
fishsticks:
; mov [EBP - 4], 0 ; Mid = 0
mov [EBP - 4], EDI ; Mid = low
add [EBP - 4], ECX ; Mid = low + high
mov EAX, [EBP - 4] ; EAX = Mid == (low + high)
mov EDX, 2
div EDX ; Mid / 2
mov [EBP - 4], EAX ; Move quotient into Mid
mov EDX, 0
strawberry:
imul EAX, 4 ; Multiply quotient by 4 to get dwords
add ESI, EAX ; Move the pointer to mid
cmp [ESI], EBX ; Compare mid to value
je dorritos
jmp ducksauce
dorritos:
mov EAX, [ESI]
jmp last
ducksauce:
cmp EBX, [ESI]
jl search1
jmp search2
search1
mov EBX, 0
mov EBX, [EBP + 4]
push EBX
mov ECX, 0
mov ECX, [EBP - 4]
sub ECX, -1
push ECX
mov EDX, 0
mov EDX, [EBP + 12]
push EDX
mov EDI, 0
mov EDI, [EBP + 16]
push EDI
call search
add ESP, 16
search2:
mov EBX, 0
mov EBX, [EBP + 4]
push EBX
mov ECX, 0
mov ECX, [EBP + 8]
push ECX
mov EDX, 0
mov EDX, [EBP - 4]
add EDX, 1
push EDX
mov EDI, 0
mov EDI, [EBP + 16]
push EDI
call search
add ESP, 16
last: add ESP, 4
mov ESP, EBP
pop EBP
ret
```

The easiest part of the program is the hardest for me, because I took courses in java instead of C. So I need to write a main program which uses scanf to initialize the elements of the array, then use a sort algorithm to sort the array and store the lowest (array[0]) and the highest (array[n-1]). Then the program needs to prompt the user for the desired value which they want to search and call the assembly search function.

Please help,

Thank You