I have crated a very simple selection sort code with c and python both (to confirm the cause)
the idea was very simple, and that was to find the difference in Runtime and Memory usage to find the better method Recursion or Loop in this case.
Surprisingly, The memory consumption for Recursion both in c and python was lesser than the usage with loop.
here is the code with both c and python that I used.
in C
loop method
#include <stdio.h>void select_sort(int *_a){ for(int i = 0; i < 10; i ++){ for(int j = i; j < 10; j++){ if(*(_a + j) < *(_a + i)){ int temp = *(_a + i); *(_a + i) = *(_a + j); *(_a + j) = temp; } } }}int main() { int a[10] = {9,8,4,33,45,65,67,87,23,45}; select_sort(&a); for(int i = 0; i < 10; i++)printf("%d ",*(a + i)); return 0;}
recursion method
#include <stdio.h>void select_sort(int *_a){ sort(_a,0);}void sort(int *_a, int k){ if(k < 9){ for(int i = k + 1; i < 10; i++){ if(*(_a) > *(_a + i)){ int temp = *(_a); *(_a) = *(_a + i); *(_a + i) = temp; } sort(_a,k+1); } }}int main() { int a[10] = {9,8,4,33,45,65,67,87,23,45}; select_sort(&a); for(int i = 0; i < 10; i++)printf("%d ",*(a + i)); return 0;}
Results with loopResults with Recursion
in Pythonloop method
def select_sort(arr): for i in range(0,len(arr)): small = i for j in range(i,len(arr)): if arr[j] < arr[small]: small = j arr[i],arr[small] = arr[small],arr[i] return arrarr = [1,3,5,8,56,764,6,75,468,4,5]print(select_sort(arr))
recursion method
def select_sort(arr): sort(arr,0)def sort(arr,k): if k < len(arr)-1: small = k for j in range(k,len(arr)): if arr[j] < arr[small]: small = j arr[k],arr[small] = arr[small],arr[k] sort(arr,k+1)arr = [1,3,5,8,56,764,6,75,468,4,5]select_sort(arr)print(arr)
Result with loopResult with recursion
My question is whyRecursion is supposed to use more Memory, since it adds an extra layer of memory to the stack.