2017-09-22 20 views
0

私は配列のソートプログラムを開発しています。このソートプログラムでは、ユーザーが入力した配列を新しい配列にコピーして変異させます。しかし、私はそれを正しく行っているかどうかは分かりません。MIPSプログラムでソート用の配列を正しくコピーしていないのですか?

.globl main 

.data 

input: .asciiz "Enter the size of the array: \n" 

entries: .asciiz "Enter the elements of the array, one line at a time: \n" 

output: .asciiz "Original array and then sorted array: \n" 

space: .asciiz " " 


.text 

main: 

    subi $sp, $sp 32 

    sw $ra, 0($sp) 

    sw $t0, 4($sp) # the size of the array 

    sw $t4, 8($sp) # the number 4 

    sw $t1, 12($sp) # temporary 

    sw $t2, 16($sp) # array original 

    sw $t3, 20($sp) # specific element 

    sw $s1, 24($sp) # copied array 

    sw $t5, 28($sp) # number to copy 

    la $a0, input 

    li $v0, 4 

    syscall 

    # get the size 

    li $v0, 5 
    syscall 
    move $t0, $v0 

    # allocate space for the array on the heap 
    li $t4, 4 
    mul $t1, $t0, $t4 
    li $v0, 9 
    move $a0, $t1 
    syscall 
    move $t2, $v0 

    li $s0, 0 
    la $a0, entries 
    li $v0, 4 
    syscall 

read_array: 
    # read element 
    li $v0, 5 
    syscall 
    move $t3, $v0 

    # place in right address 
    mul $t1, $s0, $t4 
    add $t1, $t2, $t1 
    sw $t3, 0($t2) 

    addi $s0, $s0, 1 
    blt $s0, $t0, read_array 

    li $s0, 0 

gnome_sort: 
    # allocate space on heap for copy 
    mul $t1, $t0, $t4 
    li $v0, 9 
    move $a0, $t1 
    syscall 
    move $s1, $v0 

    mul $s2, $t4, $t0 
    add $s3, $s1, $s2 

copy_array: 
    lw $t5, 0($t2) 
    sw $t5, 0($s1) 

    add $t2, $t2, $t4 
    add $s1, $s1, $t4 

    blt $s1, $s3, copy_array 

    li $s0, 0 
    while_loop: 
    bgt $s0, $t0, finish_sort 
    beq $s0, $zero, increase_i 
    sw $s4, 0($s1) 
    sw $s5, -4($s1) 
    bge $s4, $s5, increase_i 
    j swap_elements 

    increase_i: 
    addi $s0, $s0, 1 
    j while_loop    

    swap_elements: 
    la $a0, input 
    li $v0, 4 
    syscall 

    sw $t6, 0($s1) 
    sw $t7, -4($s1) 
    lw $t7, 0($s1)  
    lw $t6, -4($s1) 
    subi $s0, $s0, 1 

    j while_loop 

    finish_sort: 
    li $s0, 0 

    la $a0, output 
    li $v0, 4 
    syscall 
    j print_original 

print_original: 

    bge $s0, $t0, print_sorted 
    lw $s6, 0($t2) 

    li $v0, 1 
    move $a0, $s6 
    syscall 

    la $a0, space 
    li $v0, 4 
    syscall 

    addi $s0, $s0, 1 
    j print_original 

print_sorted: 
    li $s0, 0 
    loop: 
    bge $s0, $t0, finish 
    lw $s6, 0($s1) 

    li $v0, 1 
    move $a0, $s6 
    syscall 

    la $a0, space 
    li $v0, 4 
    syscall 

    addi $s0, $s0, 1 
    j loop 
finish: 
    li $v0, 10 
    syscall  

答えて

1

QTSpimでこれをテストした後、あなたがwhile_loopの行sw $s4, 0($s1) に割り当てられたメモリの外に行っているようです。これは、その時点の$s1が、割り当てた2番目の配列の最後を過ぎているためです。そのメモリを使いたい場合は、syscallにする必要があります。 lwswを使って配列をコピーする方法は正しいです。

+0

正確に何かのためのSyscall? Sbrk? – cococunt

+0

はい、しかし、私は '$ s1'をその配列の先頭を指すようにリセットする必要があると思います。 –

+0

アレイのポイントをどのようにリセットしますか? – cococunt

関連する問題