汇编MIPS堆栈,保留.data

时间:2015-04-13 10:15:13

标签: sorting assembly stack mips quicksort

您好我试图使用程序集(MIPS)制作Quicksort排序算法。我对汇编很新,我在程序中如何使用堆栈时遇到了一些问题。

我想要做的是使用堆栈以使quicksort子例程递归。我这样做的问题是我在移动堆栈指针时尝试排序的数组。

以下是代码:

main:

    li $s4, 0            # Min value of the range inside the array you want to sort
    li $s5, 15           # Max value of the range inside the array that you want to sort
    add $t6, $zero, $s4  # left-value
    add $t7, $zero, $s5  # right-value
    addiu $sp, $sp, -12  # We need space for the register $ra and register $a0 
    sw $ra, 0($sp)       # A must have, if you wanna come back and avoid strange behaviour 
    sw $s4, 4($sp)
    sw $s5, 8($sp) 
    jal quickSort
    nop
    ori $v0,$zero,10     # Prepare syscall to exit program cleanly
    syscall                

quickSort:

    move $a0, $zero
    add $a0, $zero, $t6   # Min value of the range inside the array you want to sort
    move $a1, $zero
    add $a1, $zero, $t7   # Max value of the range inside the array that you want to sort
    li $t5, 4             # Temp to mult with
    move $t3, $zero
    add $t3, $a0, $a1
    div $t3, $t3, 2
    mult $t3, $t5
    mflo $t3
    lw $s0, data($t3)     # Pivot = (min size + max size) / 2

    mult $a1, $t5         # offset for min value
    mflo $s1,             # offset for array min
    mult $a2, $t5         # offset for max value
    mflo $s2              # offset for array max 

sortLoop:

    bgt $a0, $a1, endLoop # While min value is less or equal to max value
    nop
leftLoop:
    lw $t4, data($s1)
    bge $t4, $s0, rightLoop
    nop 
    add $s1, $s1, 4
    add $a0, $a0, 1
    j leftLoop
    nop
rightLoop:
    lw $t5, data($s2)
    ble $t5, $s0, switchValue
    nop
    add $s2, $s2, -4
    add $a1, $a1, -1
    j rightLoop
    nop
switchValue:
    bgt $a0, $a1, repeat
    nop
    sw $t5, data($s1)
    sw $t4, data($s2)
    add $s1, $s1, 4
    add $a0, $a0, 1
    add $s2, $s2, -4
    add $a1, $a1, -1
repeat:
    j sortLoop              
endLoop:

recursion:
    bge $s4, $a1, recursion2
    nop

    addiu $sp, $sp, -12
    sw $ra, 0($sp)
    sw $a0, 4($sp)
    sw $a1, 8($sp)

    move $t6, $zero
    add $t6, $t6, $s4        # left-value
    move $t7, $zero
    add $t7, $t7, $a1
    jal quickSort
    nop
recursion2:
    bge $a0, $s5,endSorting
    nop

    addiu $sp, $sp, -12
    sw $ra, 0($sp)
    sw $a0, 4($sp)
    sw $a1, 8($sp)

    move $t6, $zero
    add $t6, $zero, $a0
    move $t7, $zero
    add $t7, $zero, $s5
    jal quickSort
    nop     
endSorting:
    lw $ra, 0($sp)
    lw $s4, 4($sp)
    lw $s5, 8($sp)
    addi $sp, $sp, 12  
    jr $ra 
    nop

我的问题如下:

  • .data值是否也会进入堆栈?
  • 这是否正确使用了堆栈?
  • 如果没有,是否有任何好的教程或可以帮助我更好地学习它的东西?

0 个答案:

没有答案