Vinh La Kiến

48 bundles
1 file7 months ago
1

InsertionSort.asm

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
.data nums: .word 7 elems: .word 1, 4, 9, 5, 2, 7, 6 Space: .asciiz " " # 1, 2, 4, 5, 6, 7, 9 # 1, 4, 9, 5, 2, 7, 6 # 1, 5, 9, 12, 16, 19, 85 array: .asciiz "\nMy array: 1, 4, 9, 5, 2, 7, 6" key: .asciiz "\nEnter key: qa" endl: .asciiz "\n" answer: "\nKey is first found at position " noAnswer: "\nKey is not found\n" .text # s0 = position # s1 = key # s3 = end (range - 1) # s4 = rear # s7 = base address li $v0, 4 la $a0, array syscall li $v0, 4 la $a0, key syscall li $v0, 5 syscall move $s1, $v0 # s1 = input = key la $s7, elems #s7 = base address li $s4, 0 # s4 = 0 = rear lw $s3, nums # s3 = 7 addi $s3, $s3, -1 # s3 = 6 = range - 1 addi $s0, $0, -1 # s0 = -1 la $a1, elems jal insertionSort la $k0, elems li $t1, 0 Print: #print element before sort beq $t1,7,ExitPrint li $t7, 4 mult $t1, $t7 mflo $t0 # t0 = l * 4bit add $s1, $t0, $k0 # t0 = &arr[l] addi $t1, $t1,1 li $v0, 4 la $a0, Space syscall lw $a0,0($s1) li $v0, 1 syscall j Print ExitPrint: j binarySearch insertionSort: li $t1, 1 # i = 1 li $t2, 7 # length Loop1: bgt $t1, $t2, exitSort move $t3, $t1 Loop2: ble $t3, 0, ExitLoop2 move $t4, $t3 mul $t4, $t4, 4 add $t4, $t4,$a1 #&arr[j] lw $t5, 0($t4) # arr[j] lw $t6, -4($t4) # arr[j-1] bge $t5,$t6, ExitLoop2 sw $t5, -4($t4) sw $t6, 0($t4) addiu $t3, $t3,-1 j Loop2 ExitLoop2: addi $t1, $t1, 1 j Loop1 exitSort: jr $ra binarySearch: # s2 = index # s5 = a[index] blt $s3, $s4, breakSearch add $s2, $s4, $s3 # div $s2, $s2, 2 # sll $s2, $s2, 2 # add $s2, $s2, $s7 # &a[index] lw $s5, ($s2) # s5 = a[index] beq $s5, $s1, answerFound bgt $s5, $s1, decrement blt $s5, $s1, increment answerFound: sub $s2, $s2, $s7 div $s2, $s2, 4 move $s0, $s2 j breakSearch decrement: addi $s3, $s3, -1 j binarySearch increment: addi $s4, $s4, 1 j binarySearch breakSearch: beq $s0, -1, notFound j found found: li $v0, 4 la $a0, answer syscall addi $a0, $s0, 1 li $v0, 1 syscall li $v0, 10 syscall notFound: li $v0, 4 la $a0, noAnswer syscall li $v0, 10 syscall