You are on page 1of 2

; Insertion sort: sort an array of integers in ascending order ; ; The program is given ; * an n-element integer array x: x[0], x[1],

..., x[n-1] ; It sorts the array in ascending order ; ; Pseudo-code is below: ; for i := 1 to n-1 ; { y := x[i]; ; j := i-1; ; while j >= 0 && x[j] > y ; { x[j+1] := x[j]; ; j := j-1; } ; x[j+1] := y; } ; Register usage ; ; ; ; ; ; ; ; ; ; R1 R2 R3 R4 R5 R6 R7 R8 R9 Ra = constant 1 = n = i := (i>n-1) = y = j := (j<0) = x[j] := (x[j]>y) = j+1

; Initialisation lea load lea sub R1,1[R1] R2,n[R0] R3,1[R0] R2,R2,R1 ; R1 = constant 1 ; R2 = n ; R3 = i = 1 ; n := n-1

; Top of for loop ; Determine whether or not to remain in the for loop forLoop cmpgt R4,R3,R2 jumpt R4,done[R0] ; Body of for loop load R5,x[R3] sub R6,R3,R1 ; y := x[i] ; j := i-1 ; R4 := (i>n-1) ; move to done if i>=n

; Top of while loop ; Determine whether or not to remain in the while loop whileLoop cmplt R7,R6,R0 jumpt R7,continue[R0] on in the for loop load R8,x[R6] ; R7 := (j<0) ; if true, continue executing the next instructi ; R8 = x[j]

cmpgt R9,R8,R5 jumpf R9,continue[R0] ion in the for loop ; Body of while loop add Ra,R6,R1 store R8,x[Ra] sub R6,R6,R1 jump whileLoop[R0] p ; End of while loop continue add R6,R6,R1 store R5,x[R6] add R3,R3,R1 jump forLoop[R0] done trap R0,R0,R0 ; Data area n x data 10 data 9 data 8 data 7 data 6 data 5 data 4 data 3 data 2 data 1 data 14

; R9 := (x[j]>y) ; if false, continue executing the next instruct

; Ra = j+1 ; x[j+1] := x[j]; ; j := j-1; ; get back to the start of the while loo

; ; ; ;

j = j+1 x[j+1] := y i = i + 1 go to top of for loop

; terminate

You might also like