0% found this document useful (0 votes)
38 views14 pages

DAA123FINAL

DAA CGPIT

Uploaded by

malankia80
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)
38 views14 pages

DAA123FINAL

DAA CGPIT

Uploaded by

malankia80
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/ 14

Enrollment no: 202203103510439

Practical-1
Aim: Implement following algorithm in iterative and recursive manner :
A. Fibonacci Algorithm
B. Factorial algorithm
C. GCD Algorithm
Code A :-
// For Iterative
function fibonacci_Iterative(n)
{ let a = 0, b = 1, temp;
if (n === 0) return a;
if (n === 1) return b;
for (let i = 2; i <= n; i++) {
temp = a + b;
a = b;
b = temp;
}
return b;
}
// For Recursive
function fibonacci_Recursive(n)
{
if (n <= 1) {
return n;
}
return fibonacci_Recursive(n - 1) + fibonacci_Recursive(n - 2);
}
op1 = "";
op2 = "";
console.log("Name: Kinjal Patel");
console.log("Enrollment: 202203103510439");
let n = prompt("Enter the Number: ");
let currentTime = Date.now();
console.log("(Iterative) fibonacci series :");
for (let i = 0; i < n; i++)
{
op1 += fibonacci_Iterative(i) + " ";
};

UTU/CGPIT/B.TECH-IT-5B/Design Analysis and Algorithm


Enrollment no: 202203103510439

console.log(op1);
console.log("(Recursive) fibonacci series :");
for (let i = 0; i < n; i++)
{
op2 += fibonacci_Recursive(i) + " ";
};
let afterTime = Date.now();
console.log(op2);
let finalTime = afterTime - currentTime;
console.log("Time taken: ", finalTime, "s");

Output :-

Explanation :
Fibonacci Algorithm :
➔ This program calculates and prints the Fibonacci sequence up to a user-specified number `n`,
measuring the time taken to compute the sequence.
➔ It prompts the user for input, then recursively generates each Fibonacci number, logs the
sequence, and displays the total computation time.

Conclusion :
● Recursive Implementation: Demonstrates a simple recursive approach to generating
Fibonacci numbers. While easy to understand, this approach can be inefficient for larger inputs
due to exponential growth in function calls.
● Execution Time: The time taken increases significantly with the size of n, showcasing the
inefficiencies of pure recursion in generating Fibonacci sequences.

Code B :-
// For Iterative

UTU/CGPIT/B.TECH-IT-5B/Design Analysis and Algorithm


Enrollment no: 202203103510439

function factorial_Iterative(n)
{ let result = 1;
for (let i = 1; i <= n; i++) {
result *= i;
}
return result;
}
// For Recursive
function factorial_Recursive(n) {
if (n === 0) {
return 1;
} else {
return n * factorial_Recursive(n - 1);
}
}
console.log("Name: Kinjal Patel");
console.log("Enrollment: 202203103510439");
let n = prompt("Enter the Number: ");
let currentTime = Date.now();
console.log("Iteractive :");
console.log("Factorial of ", n, " is: ", factorial_Iterative(n));
console.log("Recursive :");
console.log("Factorial of ", n, " is: ", factorial_Recursive(n));
let afterTime = Date.now();
let finalTime = afterTime - currentTime;
console.log("Time taken: ", finalTime, "s");
Output :-

Explanation :
Factorial Algorithm:
➔ ThisJavaScript program calculates the factorial of a number entered by the user.

UTU/CGPIT/B.TECH-IT-5B/Design Analysis and Algorithm


Enrollment no: 202203103510439

➔ Italso measures and prints the time taken to compute the factorial.
➔ The`factorial` function multiplies numbers from 1 to `n`, and the `Date.now()` function is
used to record the computation time.

Conclusion :
● Iterative Implementation: Computes the factorial of a number by multiplying integers in a
loop. This method is efficient for calculating factorials of reasonably sized numbers.
● Execution Time: The computation time is directly related to the size of the input number. The
time measurement shows how execution time scales with input size.

Code C :-
// For Iterative
function gcdIterative(a, b)
{ let temp;
while (b !== 0)
{ temp = b;
b = a % b;
a = temp;
}
return a;
}
// For Recursive
function gcdRecursive(a, b) {
if (b === 0) {
return a;
} else {
return gcdRecursive(b, a % b);
}
}
console.log("Name: Kinjal Patel ");
console.log("Enrollment: 202203103510439");

UTU/CGPIT/B.TECH-IT-5B/Design Analysis and Algorithm


Enrollment no: 202203103510439

let currentTime = Date.now();


console.log("Iteractive :");
console.log("GCD of (4556, 138):", gcdIterative(4568, 18));
console.log("Recursive :");
console.log("GCD of (4556, 138):", gcdRecursive(4568, 18));
let afterTime = Date.now();
let finalTime = afterTime - currentTime;
console.log("Time taken: ", finalTime, "s");

Output :-

Explanation :
GCDAlgorithm:
➔ The function `gcd(a, b)` computes the greatest common divisor (GCD) of two numbers using
the Euclidean algorithm.
➔ It swaps `a` and `b` until `b` becomes zero, logging the GCD and execution time.

Conclusion :
● Iterative Implementation: Efficiently computes the greatest common divisor using the
Euclidean algorithm. The iterative approach is simple and avoids the overhead of recursive
function calls.
● Execution Time: The time taken is minimal due to the algorithm’s efficiency, and the
function provides a quick result.

UTU/CGPIT/B.TECH-IT-5B/Design Analysis and Algorithm


Enrollment no: 202203103510439

Practical-2
Aim: Following is the data of height of 10 students of Sports class in
school.Lined up in a random order in front of the teacher, who’s put to the
task of lining all up in an ascending order of height.Now your task is to help
your teacher in arranging them using the following set of data and measure
their execution time.
Height:

Code :-
function merge(arr, left, middle, right) {
// Length of both sorted sub arrays
let l1 = middle - left + 1;
let l2 = right - middle;
// Create new subarrays
let arr1 = new Array(l1);
let arr2 = new Array(l2);
// Assign values in subarrays
for (let i = 0; i < l1; ++i)
{ arr1[i] = arr[left + i];
}

for (let i = 0; i < l2; ++i)


{ arr2[i] = arr[middle + 1 + i];
}
// To traverse and modify main array
let i = 0, j = 0, k = left;

UTU/CGPIT/B.TECH-IT-5B/Design Analysis and Algorithm


Enrollment no: 202203103510439

// Assign the smaller value for sorted output


while (i < l1 && j < l2) {
if (arr1[i] < arr2[j]) {
arr[k] = arr1[i];
++i;
} else {
arr[k] = arr2[j];
j++;
} k+
+;
}
// Update the remaining elements
while (i < l1) {
arr[k] = arr1[i]; i+
+;
k++;
}
while (j < l2)
{ arr[k] = arr2[j];
j++;
k++;
}
}

// Function to implement merge sort in javaScript


function mergeSort(arr, left, right) {
if (left >= right) {

UTU/CGPIT/B.TECH-IT-5B/Design Analysis and Algorithm


Enrollment no: 202203103510439

return;
}
// Middle index to create subarray halves
let middle = left + parseInt((right - left) / 2);
// Apply mergeSort to both the halves
mergeSort(arr, left, middle);
mergeSort(arr, middle + 1, right);
// Merge both sorted parts
console.log("Steps: ", arr);
merge(arr, left, middle, right);
}
// Input array
const arr = [89, 42, 100, 93, 11, 234, 30, 82, 22, 75];
console.log("Name: Kinjal Patel ");
console.log("Enrollment: 202203103510439");
let startTime = performance.now();
// Display input array
console.log("Original array: " + arr);
// Apply merge sort function
mergeSort(arr, 0, arr.length - 1);
// Display output
console.log("After sorting: " + arr);
let endTime = performance.now();
console.log(`Execution Time: ${(endTime- startTime)} seconds`);

UTU/CGPIT/B.TECH-IT-5B/Design Analysis and Algorithm


Enrollment no: 202203103510439

Output :-

UTU/CGPIT/B.TECH-IT-5B/Design Analysis and Algorithm


Enrollment no: 202203103510439

Explanation :
➔ The program implements the Merge Sort algorithm in JavaScript, which recursively divides
the array into halves, sorts each half, and then merges the sorted halves back together.
➔ This process continues until the entire array is sorted.
➔ The provided code also prints the steps of the merge process for clarity.

Conclusion :
● The implementation of the Merge Sort algorithm effectively demonstrates the
divide-and-conquer strategy for sorting.
● Merge Sort Algorithm:
● Functionality: Recursively divides the array into halves, sorts each half, and then
merges them. This ensures that the array is sorted in O(n log n) time complexity.
● StepsDisplayed: The code provides a step-by-step view of the merge process, which
helps in understanding how the array is progressively sorted.
● Execution Time: The time complexity remains consistent regardless of the input size,
making it a reliable and efficient sorting algorithm for large datasets.

UTU/CGPIT/B.TECH-IT-5B/Design Analysis and Algorithm


Enrollment no: 202203103510439

Practical-3
Aim: Suppose you are having a set of trump cards. Each card has one letter
on it. To play a game it could be better if all trump cards are arranged. To
arrange trump cards following practice should be adopted. Take the very first
card as a key element and try to place it on its final position of arrangements.
Repeat this procedure until all the cards are arranged.

Code :-
public class InsertionSort
{ void sort(char arr[]) {
double startTime = System.nanoTime();
int n = arr.length;
for (int i = 1; i < n; ++i)
{ char key = arr[i];
int j = i - 1;
/* Move elements of arr[0..i-1], that are greater than key,
to one position ahead of their current position */
while (j >= 0 && arr[j] > key)
{ arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
printArray(arr, i);
}
System.out.print("After sorting Array : ");

UTU/CGPIT/B.TECH-IT-5B/Design Analysis and Algorithm


Enrollment no: 202203103510439

for (int i = 1; i < n; ++i)


{
System.out.print(arr[i] + " ");
}
double endTime = System.nanoTime();
double executionTime = (endTime - startTime) / 1000000000;
System.out.println("");
System.out.println("Execution time: " + executionTime + " seconds");
}
// A utility function to print array of size n
static void printArray(char arr[], int counter) {
int n = arr.length;
System.out.print("Step " + counter + ": ");
for (int i = 0; i < n; ++i) {
System.out.print(arr[i] + " ");
}
System.out.println("");
} // Driver method
public static void main(String args[])
{ System.out.println("Name: Kinjal Patel ");
System.out.println("Enrollment: 202203103510439");
char arr[] = {'D', 'W', 'A', 'S', 'E', 'U', 'G'};
System.out.print("Original Array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println(" ");

UTU/CGPIT/B.TECH-IT-5B/Design Analysis and Algorithm


Enrollment no: 202203103510439

InsertionSort obj = new InsertionSort();


obj.sort(arr);
}
}

Output :-

Explanation :
This Java program sorts an array of characters using the insertion sort algorithm, printing the
array after each step of the sorting process. The `sort` method iterates through the array, shifting
elements to their correct positions, while the `printArray` method displays the array at each
sorting attempt.

Conclusion :
● The implementation of the Insertion Sort algorithm highlights a simple, intuitive method for
sorting an array.
Insertion Sort Algorithm:
● Functionality: Sorts an array by repeatedly picking the next element and inserting it
into its correct position among previously sorted elements. This method is
straightforward and effective for small to moderately sized arrays.
● Step-by-Step Sorting: The program prints the array after each insertion, providing a
clear view of how the array is being sorted incrementally.

UTU/CGPIT/B.TECH-IT-5B/Design Analysis and Algorithm


Enrollment no: 202203103510439

● Execution Time: The algorithm’s performance can degrade with larger datasets, as its
2
time complexity is O(𝑛 ). However, for the given small array of characters, it
demonstrates its utility and effectiveness well.

UTU/CGPIT/B.TECH-IT-5B/Design Analysis and Algorithm

You might also like