subprimeloads
subprimeloads

Reputation: 392

MIPS swap two array elements

Say I have an array with 10 elements and assume the $s1 register is already loaded with the base address. How would I write a simple operation that will swap A[4] and A[9]?

So far I've come up with something which consists of using a temp register, but i'm not sure if its correct:

lw $t0, 4($s1) 
sw 4($s1), 9($s1)
sw 9($s1), $t0

Upvotes: 1

Views: 1678

Answers (1)

gusbro
gusbro

Reputation: 22585

Assuming you are trying to swap items from an array of 32-bit integers, each item in the array occupies 4 bytes. So you have to multiply each index by the element size to locate each item. And your second instruction is invalid as sw it only receives one memory address (the destination operand).

So the easiest way would be to load both items and then save them with the data exchanged:

  lw $t0, 16($s1)
  lw $t1, 36($s1)
  sw $t0, 36($s1)
  sw $t1, 16($s1)

Upvotes: 3

Related Questions