使用汇编语言中的gnome排序对整数数组进行排序

时间:2016-10-09 11:29:59

标签: assembly

如何使用汇编语言中的gnome排序对能够在渐进式学习平台(PLP)中运行的整数数组进行排序?

1 个答案:

答案 0 :(得分:0)

gnome_sort:

push $ra
addiu $t0, $a0, 4   # i = 1 or start at second item
addiu $t1, $a0, 8   # j = 2 or keep track of the next item so we can jump to
        # it when the current iteration is finished.

sll $t2, $a1, 2 # $t2 = size of array * 4
addu $t3, $a0, $t2  # address of item behind the last item of
        # input array
loop:
    beq $t0, $t3, end_loop
    nop
    lw $s1, -4($t0) # load first item in array, a[i-1]
    lw $s2, 0($t0)  # load second item in array, a[i]
    slt $t4, $s1, $s2 #$t4 = (($s1 < $s2) ? 1 : 0)
    bne $t4, $0, continue # if a[i] >= a[i-1]
    nop
    # ELSE, swap items in input array
    sw $s1, 0($t0)  
    sw $s2, -4($t0)
    # move backwards through the sorted items
    # until we find the right spot.
    addiu $t0, $t0, -4 # i = i - 1 or $t0 points to lower address
    j loop
    nop
    beq $t0, $a0, continue # i == 0 or $t0 points to first item
    nop
continue:
    move $t0, $t1 # i = j or $t0 = $t1
    addiu $t1, $t1, 4 # j = j + 1 or jump to next item in the set   
    j loop
    nop
end_loop:
    pop $ra
    return