0% found this document useful (0 votes)
12 views

Lab Solution Week 4 Recurrence Method

Uploaded by

omurabuyousuf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Lab Solution Week 4 Recurrence Method

Uploaded by

omurabuyousuf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Question One: Write a C++ function to calculate the sum of all positive integers from 1 to N recursively.

Explain the
base case and recursive step in your code, and provide an example of how to call this function to find the sum of
positive integers up to a given value.

Here's a C++ function to calculate the sum of all positive integers from 1 to N recursively:

Question one - Code Solution:

#include <iostream>
// Recursive function to calculate the sum of positive integers from 1 to N
int sumOfPositiveIntegers(int n) {
// Base case: If n is 1, return 1
if (n == 1) {
return 1;
}
// Recursive step: The sum is n plus the sum of integers from 1 to (n-1)
else {
return n + sumOfPositiveIntegers(n - 1);
}
}
int main() {
int N;
std::cout << "Enter a positive integer N: ";
std::cin >> N;
if (N <= 0) {
std::cout << "Please enter a positive integer." << std::endl;
} else {
int result = sumOfPositiveIntegers(N);
std::cout << "The sum of positive integers from 1 to " << N << " is " << result << std::endl;
}
return 0;
}

Explanation:

- The `sumOfPositiveIntegers` function takes an integer `n` as its parameter.

- In the base case, when `n` is 1, the function returns 1 because the sum of positive integers from 1 to 1 is 1.

- In the recursive step, the function calculates the sum by adding `n` to the sum of positive integers from 1 to `(n-
1)`.

Example usage:
1. If you enter `5` as the input, the program will calculate and display the sum of positive integers from 1 to 5,
which is `15`.

2. If you enter a non-positive number, the program will display an error message, asking for a positive integer
input.

This recursive function effectively computes the sum of positive integers up to a given value `N`.

Simple example using a recurrence relation, which is often used in the analysis of the running time of recursive
algorithms:

T(n) = T(n - 1) + n

T(1) = 1

The closed-form solution to this recurrence is T(n) = n (n + 1)/2 , obtained via the substitution method.

Start Coding
#include <iostream>
using namespace std;
// Recursive function to solve the recurrence relation
int T(int n) {
if(n == 1) return 1;
return T(n - 1) + n;
}
int main() {
int n;
cout << "Enter the value of n: ";
cin >> n;
cout << "Solution using recurrence: T(" << n << ") = " << T(n) << endl;
// Directly using the closed-form solution to verify
int closedFormSolution = n * (n + 1) / 2;
cout << "Solution using closed-form expression: T(" << n << ") = " << closedFormSolution << endl;
return 0;
}

Here, the `T` function calculates the recurrence relation's value using the substitution method in code, while the
`closedFormSolution` verifies this with the closed-form solution derived from the manual substitution method.

Remember, this example demonstrates a simple calculation following the substitution method in coding, and it
doesn't implement the proof of the substitution method or the derivation of the closed-form expression. The proof
and derivation are generally performed manually using mathematical induction.
Question 2: Solution for Merge Sort.
Implement in C++ code the Merge Sort that is based on the principle of Divide and
Conquer Algorithm.

#include <iostream>
using namespace std;

// Merge two subarrays L and M into arr


void merge(int arr[], int p, int q, int r) {

// Create L ← A[p..q] and M ← A[q+1..r]


int n1 = q - p + 1;
int n2 = r - q;

int L[n1], M[n2];

for (int i = 0; i < n1; i++)


L[i] = arr[p + i];
for (int j = 0; j < n2; j++)
M[j] = arr[q + 1 + j];

// Maintain current index of sub-arrays and main arrays


int i, j, k;
i = 0;
j = 0;
k = p;

// Until we reach either end of either L or M, pick larger among


// elements L and M and place them in the correct position at A[p..r]
while (i < n1 && j < n2) {
if (L[i] <= M[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = M[j];
j++;
}
k++;
}

// When we run out of elements in either L or M,


// pick up the remaining elements and put in A[p..r]
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}

while (j < n2) {


arr[k] = M[j];
j++;
k++;
}
}

// Divide the array into two subarrays, sort them and merge them
void mergeSort(int arr[], int l, int r) {
if (l < r) {
// m is the point where the array is divided into two subarrays
int m = l + (r - l) / 2;

mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);

// Merge the sorted subarrays


merge(arr, l, m, r);
}
}

// Print the array


void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}

// Driver program
int main() {
int arr[] = {6, 5, 12, 10, 9, 1};
int size = sizeof(arr) / sizeof(arr[0]);

mergeSort(arr, 0, size - 1);

cout << "Sorted array: \n";


printArray(arr, size);
return 0;
}
MergeSort (array, left, right)
Input: An array of data, and lower and upper bound of the array

Output: The sorted Array

#include<iostream>
using namespace std;
void swapping(int &a, int &b) { //swap the content of a and b
int temp;
temp = a;
a = b;
b = temp;
}
void display(int *array, int size) {
for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << endl;
}
void merge(int *array, int l, int m, int r) {
int i, j, k, nl, nr;
//size of left and right sub-arrays
nl = m-l+1; nr = r-m;
int larr[nl], rarr[nr];
//fill left and right sub-arrays
for(i = 0; i<nl; i++)
larr[i] = array[l+i];
for(j = 0; j<nr; j++)
rarr[j] = array[m+1+j];
i = 0; j = 0; k = l;
//marge temp arrays to real array
while(i < nl && j<nr) {
if(larr[i] <= rarr[j]) {
array[k] = larr[i];
i++;
}else{
array[k] = rarr[j];
j++;
}
k++;
}
while(i<nl) { //extra element in left array
array[k] = larr[i];
i++; k++;
}
while(j<nr) { //extra element in right array
array[k] = rarr[j];
j++; k++;
}
}
void mergeSort(int *array, int l, int r) {
int m;
if(l < r) {
int m = l+(r-l)/2;
// Sort first and second arrays
mergeSort(array, l, m);
mergeSort(array, m+1, r);
merge(array, l, m, r);
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n]; //create an array with given number of elements
cout << "Enter elements:" << endl;
for(int i = 0; i<n; i++) {
cin >> arr[i];
}
cout << "Array before Sorting: ";
display(arr, n);
mergeSort(arr, 0, n-1); //(n-1) for last index
cout << "Array after Sorting: ";
display(arr, n);
}
MergeSort Algorithm Pseudocode based.

#include<iostream>
using namespace std;
void swapping(int &a, int &b) { //swap the content of a and b
int temp;
temp = a;
a = b;
b = temp;
}
void display(int *array, int size) {
for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << endl;
}
void merge(int *array, int l, int m, int r) {
int i, j, k, nl, nr;
//size of left and right sub-arrays
nl = m-l+1; nr = r-m;
int larr[nl], rarr[nr];
//fill left and right sub-arrays
for(i = 0; i<nl; i++)
larr[i] = array[l+i];
for(j = 0; j<nr; j++)
rarr[j] = array[m+1+j];
i = 0; j = 0; k = l;
//marge temp arrays to real array
while(i<nl && j<nr) {
if(larr[i] <= rarr[j]) {
array[k] = larr[i];
i++;
}else{
array[k] = rarr[j];
j++;
}
k++;
}
while(i<nl) { //extra element in left array
array[k] = larr[i];
i++; k++;
}
while(j<nr) { //extra element in right array
array[k] = rarr[j];
j++; k++;
}
}
void mergeSort(int *array, int l, int r) {
int m;
if(l < r) {
int m = l+(r-l)/2;
// Sort first and second arrays
mergeSort(array, l, m);
mergeSort(array, m+1, r);
merge(array, l, m, r);
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n]; //create an array with given number of elements
cout << "Enter elements:" << endl;
for(int i = 0; i<n; i++) {
cin >> arr[i];
}
cout << "Array before Sorting: ";
display(arr, n);
mergeSort(arr, 0, n-1); //(n-1) for last index
cout << "Array after Sorting: ";
display(arr, n);
}

You might also like