1. Engineering
  2. Computer Science
  3. loops and iterations can be turned into recursions and vice...

Question: loops and iterations can be turned into recursions and vice...

Question details

Loops and iterations can be turned into recursions, and vice versa. In class, we studied iterative
implementations of selection sort. In this question, we explore a purely recursive implementation.
To do this effectively, in our mind we divide up the array called arr into two subarrays: arr[0…mid-1]
denoting the subarray from index 0 to index mid-1, and arr[mid…len-1] denoting the subarray from index
mid to len-1]. Next, we follow the following steps.
a) First, write a function called findMinpos, which recursively finds the position in the subarray
arr[mid…len-1] with the minimum value (this was called minpos in class). The function prototype is
given below. Remember: no loops allowed!
int findMinpos(int arr[], int mid, int len) {
// Finds the position in subarray arr[mid...len-1] with minimum value (minpos)
}
b) Next, write a function called swapMinpos, which swaps arr[mid] and arr[minpos]. The function
prototype is given below:
void swapMinpos(int arr[], int mid, int len) {
// Swaps minimum of subarray arr[mid...len-1] with arr[mid]
}
c) Finally, write a recursive selection sort function, called selSortR. There are many possible
implementations. For this problem, the function selSortR will put the smallest mid elements in the
array arr in sorted order in the subarray arr[0…mid-1]. The function prototype, as well as the main
function one may use to call selSortR, are given below. Remember: no loops allowed!
void selSortR(int arr[], int mid, int len) {
// Puts smallest mid elements in arr in sorted order in arr[0...mid-1];
}
void main() {
int arr[14] = {488888, 3, 5, 0, 23, 12124, 6, 7, 2, 1121, 0, 92, 5, 8};
selSortR(arr, 14, 14);
/* This will put the smallest 14 elements in the first 14 positions,
which will sort the entire array */
for (int i = 0; i<14; i++) {
printf("arr[%d] = %d\n", i, arr[i]);
}
}

Solution by an expert tutor
Blurred Solution
This question has been solved
Subscribe to see this solution