Download presentation
Presentation is loading. Please wait.
1
Assembly 06 Recursion
2
A recursive procedure calls itself
Directly : the procedure calls itself directly Indirectly : the procedure P makes a call to procedure Q, which in turn calls procedure P. Example: n! = n(n-1)! ; n = 0 factorial(i) = n * factorial(n − 1); n > 0 int fact(int n) { if (n == 0) return(1); return(n * fact(n-1)); }
3
factorial
4
factorial %include "io.mac" .DATA
prompt_msg db "Please enter a positive integer: ",0 output_msg db "The factorial is: ",0 error_msg db "Sorry! Not a positive number. Try again.",0 .CODE .STARTUP PutStr prompt_msg ; get n GetInt BX ; read number into BX call fact PutStr output_msg ; output n! PutInt AX .EXIT Example
5
factorial ; It receives a positive integer n in BX register.
; It returns n! in AX register. .CODE fact: cmp BL,1 ; if N > 1, recourse jg one_up mov AX,1 ; return 1 for N < 2 ret ; terminate recursion one_up: dec BL ; recurse with (N-1) call fact inc BL mul BL ; AX = AL * BL ret
6
QuickSort
7
Quick Sort public void quickSort(int array[], int start, int end) {
int i = start; int k = end; if (end - start >= 1) { // more than on element int pivot = array[start]; // set the pivot as the first element while (k > i) { while (array[i] <= pivot && i <= end && k > i) // left to right scan i++; while (array[k] > pivot && k >= start && k >= i) // right to left scan k--; // element not greater than the pivot if (k > i) swap(array, i, k); // the right index, swap the corresponding elements } swap(array, start, k); // after cross, swap the last element in quickSort(array, start, k - 1); // quicksort the left partition quickSort(array, k + 1, end); // quicksort the right partition else { // one element return;
8
Quick Sort QuckSort: pushad cmp EDI, ESI
jle qsort_done ; end recursion if hi <= lo ; save hi and lo for later use mov ECX, ESI mov EDX, EDI mov AX,[EBX+EDI*2] ; AX = xsep lo_loop: cmp [EBX+ESI*2],AX ; jge lo_loop_done ; LO while loop inc ESI jmp lo_loop lo_loop_done: dec EDI ; hi = hi-1 hi_loop: jle sep_done cmp [EBX+EDI*2],AX ; HI while loop jle hi_loop_done ; dec EDI ; jmp hi_loop ;
9
Quick Sort hi_loop_done: xchg AX, [EBX+ESI*2]
xchg AX, [EBX+EDI*2] ; x[i] <=> x[j] jmp lo_loop sep_done: xchg AX, [EBX+EDX*2] ; x[i] <=> x[hi] dec ESI mov EDI, ESI ; hi = i-1 ; ESI value will be modified in the next statement, as the original ESI value is in EDI, ; EDI value is used to get i+1 value for the second qsort call. mov ESI,ECX call qsort inc EDI ;EDI has the i value inc EDI mov ESI,EDI ; lo = i+1 mov EDI,EDX qsort_done: popad ret
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.