Write a program to merge two sorted arrays to create a third sorted array contai
ID: 3548316 • Letter: W
Question
Write a program to merge two sorted arrays to create a third sorted array containing all values from the two original arrays. PLEASE INCLUDE COMMENTS !!!
Merge is a key component to the mergesort algorithm. Suppose we have two sorted array A and B. We want to create array C which contains all values from A and B, in sorted order. Merge looks at one element from each of A and B, and puts the smaller one into array C. When all elements of A or B have been copied into C, the remaining elements from the other array are copied into C.
The pseudocode for merge is:
Hint: Think carefully about the subscripts you need for the three arrays.
Explanation / Answer
.data
A: .space 7 #space for 7 ints
B: .space 5 #space for 7 ints
C: .space 12 #space for 7 ints
prompt1: .asciiz "Enter next integer to put into A :"
prompt2: .asciiz "Enter next integer to put into B :"
text: .asciiz "After merging, the list of integers is:"
space: .asciiz " "
.text
.globl main
main:
la $a1, A #load address of A to a1
la $a2, B #load address of B to a2
la $s0, C #load address of C to s0
#Taking inputs from user and inserting in A
li $t0, 7
p1:
beqz $t0,p2 #if 7 inputs taken then exit loop
li $v0, 4
la $a0, prompt1
syscall #display prompt message
li $v0, 5
syscall
sw $v0, 0($a1) #store into array
addi $a1, $a1, 4 #point to next element in array
addi $t0,$t0,-1
j p1
#same as above for B
li $t0, 5
p2:
beqz $t0,sort
li $v0, 4
la $a0, prompt2
syscall
li $v0, 5
syscall
sw $v0, 0($a2)
addi $a2, $a2, 4
addi $t0,$t0,-1
j p2
#merging part
sort:
la $a1, A
la $a2, B
li $t0, 12
sortmain:
beqz $t0,end
lw $s0,0($a1)
lw $s1,0($a2)
slt $t1,$s0,$s1
beqz $t1,s1
#if element in a is smaller than elem in b
sw $s0,0(s0)
addi $a1, $a1, 4
addi $s0, $s0, 4
addi $t0,$t0,-1
j sortmain
#if element in b is smaller than elem in a
s1:
sw $s1,0(s0)
addi $a2, $a2, 4
addi $s0, $s0, 4
addi $t0,$t0,-1
j sortmain
#final printing
end:
li $v0, 4
la $a0, text
syscall
la $a3, C
li $t0, 12
#loop for printing 12 numbers
print:
beqz $t0,exit
lw $a0,0($a3)
li $v0,1
syscall
li $v0, 4
la $a0, space
syscall
addiu $a3, $a3, 4
addi $t0,$t0,-1
j print
exit
li $v0, 10
syscall
#The comments are not complete but they should give you a rough idea. As i said am in a hurry rite now.
#Have rectified the errors. See if they work.. beq was a typo it should be beqz
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.