Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

DESIGN &

ANALYSIS OF

ALGORITHMS

PRACTICAL

FILE
AATMASHRI SANYAL

2022UPD9503

QUESTION 1

ALGORITHMS

1) To convert a decimal number, n, to binary format

Step 1: Initialize an empty string to store the binary input (binary=””)

Step 2: While n is greater than 0

Find the remainder when n is divided by 2 (remainder=n%2)

Step 3: Add the remainder (as a string) to the binary string (binary=str(remainder) + binary)

Step 4: Update n by dividing it by 2 discarding the decimal part (n//=2)

Step 5: Return the binary string (binary)

2)To find the average age of a group of 10 players

Step 1: Calculate the sum of all ages in the list (total age=sum(players age))

Step 2: Divide the total age by the number of players (average=total age/len(players age))

Step 3: Return the average age (average)

3)To calculate even numbers between 0 and 99

Step 1: Initialize variable flag=0

Step 2: Run a for loop with the following conditions (int i=0, i<=99;i++)

Step 3: If i%2==0, which checks if and when i is divided by 2, the remainder is 0, that will only
happen if it's an even number

Increment variable flag by 1, flag ++

Step 4: Return flag


















QUESTION 2

FLOWCHART

1) Sum of first 100 natural numbers.


















Start

N = 1

Sum = 0

Sum = Sum + N

N = N + 1

Yes
If N<=100

No

Print Sum

Stop
2)To find the largest of three numbers x, y and z.

Start

Read

A, B, C

No Is
Yes

A>B

Yes Is
No No Is
Yes

B>C A>B

B is largest C is largest A is largest

Stop
3) To generate first 50 items of the Fibonacci series

Start

i=0

j=0

k=0

fib=0

No
i<50?

Yes
Output end
“Fibonacci(i)=fib”

Output carriage
return and linefeed

fib=j+k

j=k

k=fib

i=i+1
4)To convert temperature Fahrenheit to Celsius.

Start

Read F

C=(5+(F-32))/9

Print C

Stop
5)To print even numbers between 9 and 100

Start

N=2

Yes
N>100? Stop

No

Print N

N=N+2
QUESTION 3

PROGRAM

Write a code to calculate factorial of a given number using recursion.

















CODE

OUTPUT
QUESTION 4

PROGRAM

Write a code to generate Fibonacci series.

















CODE

OUTPUT
QUESTION 5

PSEUDOCODE

1)Linear Search

procedure linear_search (list, value)


for each item in the list


if match item == value


return the item's location


end if


end for


end procedure

2)Binary Search

function binary_search(list, target):

left = 0

right = length(list) - 1

while left <= right:

mid = (left + right) // 2

if list[mid] == target:

return mid

elif list[mid] < target:

left = mid + 1

else:

right = mid - 1

return -1















QUESTION 6

PROGRAM

Write a code to implement the concept of Linear search.

CODE

OUTPUT
QUESTION 7

PROGRAM

Write a code to implement the concept of Binary search.

CODE

OUTPUT
QUESTION 8

PSEUDOCODE

1)Bubble Sort

function bubbleSort(arr)

n <- length(arr)

swapped := true

while swapped do

swapped := false

for i := 1 to n - 1 do

if arr[i] > arr[i + 1] then

swap(arr[i], arr[i + 1])

swapped := true

end if

end for

end while

end function


function swap(a, b)

temp := a

a := b

b := temp

end function

2)Selection Sort

function selectionSort(arr)

n <- length(arr)

for i := 0 to n-1 do

minIndex := i // Initialize minimum index as current position

for j := i + 1 to n-1 do // Loop through the unsorted part

if arr[j] < arr[minIndex] then

minIndex := j // Update minimum index if a smaller element is found

end if

end for

swap(arr[i], arr[minIndex]) // Swap the found minimum element with the current element

end for

end function


function swap(a, b)

temp := a

a := b

b := temp

end function















3)Merge Sort

function mergeSort(arr, left, right)


if left < right then


mid := (left + right) // 2 // Avoid overflow, use integer division


mergeSort(arr, left, mid) // Sort left half


mergeSort(arr, mid + 1, right) // Sort right half


merge(arr, left, mid, right) // Merge the sorted halves


end if


end function


function merge(arr, left, mid, right)


n1 := mid - left + 1


n2 := right - mid


leftArr[1..n1] := copy(arr[left..mid])


rightArr[1..n2] := copy(arr[mid + 1..right])


i := 1


j := 1


k := left


while i <= n1 and j <= n2 do


if leftArr[i] <= rightArr[j] then


arr[k] := leftArr[i]


i := i + 1


else


arr[k] := rightArr[j]


j := j + 1


end if


k := k + 1


end while


while i <= n1 do


arr[k] := leftArr[i]


i := i + 1


k := k + 1


end while


while j <= n2 do


arr[k] := rightArr[j]


j := j + 1


k := k + 1


end while


end function















4)Quick Sort

function quickSort(arr, left, right)



if left < right then

pivotIndex := partition(arr, left, right)

quickSort(arr, left, pivotIndex - 1) // Sort left half

quickSort(arr, pivotIndex + 1, right) // Sort right half

end if

end function

function partition(arr, left, right)

pivot := arr[right] // Choose the rightmost element as pivot (other choices possible)

i := left - 1

for j := left to right - 1 do

if arr[j] <= pivot then

i := i + 1

swap(arr[i], arr[j])

end if

end for


swap(arr[i + 1], pivot) // Place pivot in its correct position

return i + 1

end function


function swap(a, b)

temp := a

a := b

b := temp

end function















QUESTION 9

PROGRAM

Write a code to implement the concept of Bubble Sort.


CODE

OUTPUT
QUESTION 10

PROGRAM

Write a code to implement the concept of Selection sort.

CODE

OUTPUT
QUESTION 11

PROGRAM

Write a code to implement the concept of Merge sort.

CODE
OUTPUT
QUESTION 12

PROGRAM

Write a code to implement the concept of Quick sort.

CODE
OUTPUT
QUESTION 13

Write an algorithm and pseudocode for the following:

Kruskal’s algorithm

ALGORITHM

Step 1: Sort all the edges in non-decreasing order of their weight.

Step 2: Initialize an empty minimum spanning tree.

Step 3: Iterate through each edge in the sorted order: a. If adding the edge to the minimum
spanning tree does not form a cycle, add it to the minimum spanning tree. b. Otherwise, discard
the edge.

Step 4: Repeat step 3 until there are (V - 1) edges in the minimum spanning tree, where V is the
number of vertices in the graph.

PSEUDOCODE

KRUSKAL(G):

A = ∅ ϴ

For each vertex v ∈ G.V:

MAKE-SET(v)

For each edge (u, v) ∈ G.E ordered by increasing order by weight(u, v):

if FIND-SET(u) ≠ FIND-SET(v):

A = A ∪ {(u, v)}

UNION(u, v)

return A
PRIM’S ALGORITHM

ALGORITHM

Step 1: Initialize an empty spanning tree and a priority queue.

Step 2: Add an arbitrary vertex to the spanning tree.

Step 3: While there are still vertices not in the spanning tree:

Select the edge with the minimum weight that connects a vertex in the spanning tree to a
vertex, not in the spanning tree.

Add the selected edge and the connected vertex to the spanning tree.

Step 4: Repeat step 3 until all vertices are in the spanning tree.

PSEUDOCODE

prim(graph):

mst = empty set


startVertex = first vertex in graph

mst.add(startVertex)


edges = edges connected to startVertex


while mst has fewer vertices than graph:



minEdge, minWeight = findMinEdge(edges)


mst.add(minEdge)


for edge in edges connected to minEdge:

if edge is not in mst:

edges.add(edge)


edges.remove(minEdge)


return mst as an array
QUESTION 14

PROGRAM

Fractional knapsack problem


CODE
OUTPUT
PROGRAM

Fractional knapsack problem

CODE

OUTPUT
QUESTION 15

TURTLE PROGRAMMING

Draw the following figures using Turtle programming in Python:



Square

Triangle

Circle

Rectangle

Dot
CODE
QUESTION 16

TURTLE PROGRAMMING

Draw the following figures using Turtle programming in Python:



Square

Triangle

Circle

Rectangle

Dot
CODE
QUESTION 17

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>My First HTML Page</title>

<style>

/* Inline CSS */

.bold {

font-weight: bold;

.italic {

font-style: italic;

.underline {

text-decoration: underline;

.superscript {

vertical-align: super;

.subscript {

vertical-align: sub;

.emphasized {

font-style: italic;

font-weight: bold;

.strong {

font-weight: bolder;

</style>

</head>

<body>

<h1>This is a Heading 1</h1>

<h2>This is a Heading 2</h2>

<h3>This is a Heading 3</h3>

<h4>This is a Heading 4</h4>

<h5>This is a Heading 5</h5>

<h6>This is a Heading 6</h6>

<p>This is a <b class="bold">bold</b> text.</p>

<p>This is an <i class="italic">italic</i> text.</p>

<p>This is an <u class="underline">underlined</u> text.</p>

<p>This is a <sup class="superscript">superscript</sup> and this is a <sub

class="subscript">subscript</sub>.</p>

<p><em class="emphasized">This is emphasized text</em>, and this is <strong class="strong">strong</

strong> text.</p>

<br>

<hr>

<font color="red" face="Arial" size="4">This is a text with custom font, color, and size</font>

<p style="text-align: center;">This text is aligned center.</p>

<p style="background-color: yellow;">This text has a yellow background color.</p>

<pre>

This is preformatted text.

It preserves spaces and line breaks.

</pre>

<h3>List Examples</h3>

<h4>Ordered List</h4>

<ol>

<li>Item 1</li>

<li>Item 2</li>

<li>Item 3</li>

</ol>

<h4>Unordered List</h4>

<ul>

<li>Item A</li>

<li>Item B</li>

<li>Item C</li>

</ul>

<h3>Colors</h3>

<p style="color: blue;">This text is blue.</p>

<h3>Images</h3>

<img src="image.jpg" alt="Sample Image" width="200" height="150">

<h3>Tables</h3>

<table border="1">

<tr>

<th>Header 1</th>

<th>Header 2</th>

<th>Header 3</th>

</tr>

<tr>

<td>Row 1, Col 1</td>

<td>Row 1, Col 2</td>

<td>Row 1, Col 3</td>

</tr>

<tr>

<td>Row 2, Col 1</td>

<td>Row 2, Col 2</td>

<td>Row 2, Col 3</td>

</tr>

</table>

<h3>Hyperlinks</h3>

<a href="https://www.example.com">Visit Example Website</a>

</body>

</html>

QUESTION 18

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Internal CSS Example</title>

<style>

/* Changing Colors */

.text-red {

color: red;

.bg-green {

background-color: green;

/* Changing Borders */

.border-example {

border: 2px solid blue;

/* Changing Margins */

.margin-example {

margin: 20px;

/* Changing Padding */

.padding-example {

padding: 10px;

/* Changing Box Model */

.box-example {

border: 2px solid black;

padding: 10px;

margin: 20px;

/* Changing Outline */

.outline-example {

outline: 2px dotted red;

/* Changing Text */

.text-example {

font-size: 20px;

font-weight: bold;

text-decoration: underline;

/* Changing Fonts */

.font-example {

font-family: Arial, sans-serif;

</style>

</head>

<body>

<!-- Colors -->

<p class="text-red">This text is red.</p>

<div class="bg-green">This has a green background.</div>

<!-- Borders -->

<div class="border-example">This has a blue border.</div>

<!-- Margins -->

<div class="margin-example">This has a margin of 20px.</div>

<!-- Padding -->

<div class="padding-example">This has a padding of 10px.</div>

<!-- Box Model -->

<div class="box-example">This demonstrates the box model.</div>

<!-- Outline -->

<div class="outline-example">This has a red dotted outline.</div>

<!-- Text -->

<p class="text-example">This text has custom styling.</p>

<!-- Fonts -->

<p class="font-example">This text uses Arial font.</p>

</body>

</html>

QUESTION 18

CASE STUDIES

1)Algorithms and their impact on product Design.

Social media platforms have become an undeniable force in our lives, and the invisible
hand shaping them is the power of algorithms. Let's delve deeper into how algorithms
influence every aspect of a social media platform, from the content you see to the way you
interact.

Personalized Feeds: An Echo Chamber Tailored Just for You

Imagine walking into a bookstore where every shelf is stocked with your favorite
genres. That's the power of personalized feeds. Social media platforms employ sophisticated
algorithms that analyze your past interactions, likes, comments, and even demographic
information. By understanding what piques your interest, the algorithm prioritizes content that
resonates most with you. This could be news articles on topics you follow, funny cat videos
that tickle your fancy, or even content from friends you haven't interacted with in a while but
share similar interests.

These algorithms aren't static. They leverage machine learning, a branch of artificial
intelligence, to continuously learn and refine their recommendations based on your evolving
behavior. The more you engage, the more the algorithm tailors your feed, potentially creating
an "echo chamber" where you're primarily exposed to information that confirms your existing
beliefs. This can be beneficial for surfacing content you enjoy, but it also raises concerns
about exposure to diverse viewpoints.

Content Moderation: The Balancing Act of Free Speech and Safety

Social media platforms strive to be vibrant marketplaces of ideas, but maintaining a


safe and positive environment is crucial. Here's where algorithms step in as digital bouncers.
Natural Language Processing (NLP) algorithms analyze text-based content for hate speech,
bullying, or misinformation. They can identify potentially offensive language patterns and flag
content for human moderators to review.

Image and video recognition algorithms play a similar role, scanning for harmful content
like violence or graphic imagery. These algorithms are constantly evolving, adapting to new
trends and emerging threats. However, the line between filtering harmful content and stifling
free speech can be blurry. Striking the right balance remains a challenge for social media
platforms and their algorithms.

Targeted Advertising: When Ads Feel Less Like Intrusions

Have you ever noticed a surge of ads for hiking gear after browsing travel websites for
a weekend getaway? That's not a coincidence. Social media platforms leverage algorithms to
analyze your user data, including demographics, interests, and browsing history, to identify
potential customers for advertisers. By delivering targeted ads that align with your recent
interests, the platform creates a win-win situation. Users experience less intrusive advertising,
and advertisers reach the most relevant audience, maximizing their return on investment.

Recommendation Systems: Fostering Connections and Keeping You Engaged

Social media is all about connecting with like-minded people and discovering new
content. Recommendation systems powered by algorithms play a key role in facilitating this.
These algorithms analyze your preferences and interactions within your network to suggest
new connections, groups, or content that you might find interesting.

Collaborative filtering, a subfield of machine learning, lies at the heart of these


recommendations. By identifying patterns in user behavior across the platform, the algorithm
can connect users with similar interests, even if they haven't interacted before. This fosters a
sense of community and keeps you engaged by constantly introducing fresh content to
explore.

2)Use of Algorithms to Generate Patterns

Algorithms are widely used to generate intricate and visually appealing patterns across
various domains, including art, design, and technology. Let's explore the application of
algorithms in generating patterns through the example of generative art:

Generative Art: Generative art refers to artwork created using algorithms, often with the goal
of exploring randomness, complexity, and emergent behavior. Algorithms play a fundamental
role in generating patterns, shapes, and compositions, enabling artists and designers to
produce unique and visually captivating artworks
Algorithmic Composition
Music composition algorithms use mathematical models, such as Markov chains or
fractal geometry, to generate melodies, harmonies, and rhythms. These algorithms
introduce elements of randomness and variation, resulting in diverse and evolving
musical patterns
Artists can experiment with different parameters and algorithms to create compositions
that range from structured and melodic to abstract and experimental
Procedural Generation
Procedural generation algorithms are used in video game development, digital art, and
virtual environments to generate terrain, landscapes, and textures. By defining rules and
parameters, these algorithms can create complex and realistic patterns that mimic
natural phenomena
Fractal algorithms, such as the Mandelbrot set or Perlin noise, are commonly used to
generate intricate and self-similar patterns with varying levels of detail
Generative Design
Generative design algorithms are employed in architecture, product design, and
manufacturing to explore and optimize design solutions. By specifying design goals and
constraints, these algorithms can generate a range of alternative designs that meet
predefined criteria
Evolutionary algorithms, genetic algorithms, and artificial neural networks are used to
iteratively generate, evaluate, and refine design solutions, leading to innovative and
efficient outcomes
Computational Art
Computational artists use programming languages and algorithms to create interactive
and dynamic artworks that respond to user input or environmental stimuli. These
artworks often explore concepts of interactivity, generativity, and emergence
Artists combine code, data, and algorithms to produce interactive installations, digital
sculptures, and immersive experiences that challenge traditional notions of art and
creativity.

In conclusion, algorithms enable artists, designers, and technologists to explore new forms of
expression, creativity, and innovation in generating patterns and artworks. By embracing
algorithms as creative tools, practitioners can push the boundaries of art and design, creating
compelling and thought-provoking experiences for audiences worldwide.

You might also like