2017-09-22 2 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은 할당 한 두 번째 배열의 끝을 지나기 때문입니다. 해당 메모리를 사용하려면 syscall을 사용해야합니다. lwsw을 사용하여 배열을 복사하는 방법이 정확합니다.

+0

정확히 무엇을위한 Syscall입니까? Sbrk? – cococunt

+0

네,하지만'$ s1'을 다시 배열의 처음을 가리 키도록 재설정해야한다고 생각합니다. –

+0

배열의 포인트를 어떻게 재설정합니까? – cococunt

관련 문제