# MIPS Binary Search Algorithm w/ Arrays
.data
array: .space 404
p1: .asciiz "\nEnter the data for a sorted array: "
p2: .asciiz "\nEnter a value to search for: "
p3: .asciiz " is not found"
p4: .asciiz " is found at "
.text
main:
la $s0, array # s0 = addr of first int
addi $t0, $zero, 0 # t0 = 0 counter
addi $s1, $zero, 0 # s1 = 0 array size counter
#Store Array Values
store:
li $v0, 4 # system call code for print_str
la $a0, p1 # address of string to print
syscall # print the first prompt
li $v0, 5 # system call for read_int
syscall # read int to store
beq $v0, 0, searchP # once sentinel val hit, go to search
j storeVal # store int in array if !=0
storeVal:
add $t1, $zero, $t0 #offset in t1
add $t1, $t1, $t1 #t1*2
add $t1, $t1, $t1 #t1*4
add $s2, $t1, $s0 #array with offset in s2
sw $v0, 0($s2) #save int
addi $t0, $t0, 1 # counter++
addi $s1, $s1, 1 # array size counter++
lw $t9, ($s0) # loads addr of array
add $t9, $t9, $s0 # goes to addr of end of array
sub $t9, $t9, 4 # goes back 4 to beginning of last array val
j store # continue to add integers
#Binary Search
searchP:
li $v0, 4 # system call code for print_str
la $a0, p2 # address of string to print
syscall # print the second prompt
li $v0, 5 # system call for read_int
syscall # read int to find
move $a0, $v0 # store int to find
beq $a0, 0, end # once sentinel val hit, go to end prog
la $a1, array # a1 = addr of first int
add $a2, $a1, $t9 # a2 = addr of last int
bsearch:
subu $sp, $sp, 4 # 4 bytes 4 stack
sw $ra, 4($sp) # save return addr
subu $t0, $a2, $a1 # size of array
bnez $t0, searchVal # if not 0, search
move $v0, $a1 # addr of only entry
lw $t0, ($v0) # load entry
beq $a0, $t0, found # if = to int, print found
j notFound # not found
searchVal:
sra $t0, $t0, 3 # comp offset of middle m:
sll $t0, $t0, 2 # t0 = 4(t1/8)
addu $v0, $a1, $t0 # middle m
lw $t0, ($v0) # t0 = m
beq $a0, $t0, found # if = to int, print found
blt $a0, $t0, left # search left
j right # search right
right:
addu $a1, $v0, 4 # search right
jal bsearch
beq $a0, $t0, found # if = to int, print found
j notFound # not found
left:
move $a2, $v0 # search left of m
jal bsearch
beq $a0, $t0, found # if = to int, print found
j notFound # not found
#Print
found:
li $v0, 1 # system call code for print_int
move $a0, $s2 # integer to print (counter)
syscall # print it
li $v0, 4 # system call code for print_str
la $a0, p4 # address of string to print
syscall # print the answer part 2
j searchP # continue to search for more integers
notFound:
li $v0, 1 # system call code for print_int
move $a0, $s2 # integer to print (counter)
syscall # print it
li $v0, 4 # system call code for print_str
la $a0, p3 # address of string to print
syscall # print the answer part 2
j searchP # continue to search for more integers
#END PROG
end:
li $v0, 10
syscall
我终于让数组接受输入,但是现在我的二进制搜索永远是循环的,它永远不会打到print语句。我觉得这与$ t9(在storeVal :)中有关,而且没有正确找到数组的结尾,但我不确定我该怎么做。
编辑:输入1,2,3,4,5,0适用于数组,搜索1或2都返回'268501008'找到'。搜索3将其发送到无限循环中......仍然不确定我在哪里弄乱。