0% found this document useful (0 votes)
21 views59 pages

Chandan Daa File

The document outlines five practical programming tasks involving algorithms such as binary search, merge sort, quick sort, the greedy approach for the 0/1 knapsack problem, and Prim's algorithm for finding the minimum spanning tree. Each task includes a detailed algorithm and a corresponding C++ program to implement the solution. The programs demonstrate efficient data handling and sorting techniques, along with performance measurement for sorting algorithms.

Uploaded by

officialaman1125
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)
21 views59 pages

Chandan Daa File

The document outlines five practical programming tasks involving algorithms such as binary search, merge sort, quick sort, the greedy approach for the 0/1 knapsack problem, and Prim's algorithm for finding the minimum spanning tree. Each task includes a detailed algorithm and a corresponding C++ program to implement the solution. The programs demonstrate efficient data handling and sorting techniques, along with performance measurement for sorting algorithms.

Uploaded by

officialaman1125
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/ 59

PRACTICAL NO.

1
Write a program to find out a roll number from college database using
binary search algorithm.
By sorting the list of roll numbers and then applying binary search, the program efficiently finds
whether a specific roll number exists in the list and provides its position. This combination of
sorting and binary search ensures optimal search performance in terms of time complexity.

ALGORITHM:

The algorithm for the given program is given below, from where we easily get to know about how
this particular program will work.

1. Input the number of students: Read the number of students (num) in the college.

2. Input roll numbers: Create an array Arr of size num to store the roll numbers of the
students. Loop through the array and input each roll number.

3. Sort the array: Sort the array Arr in ascending order to prepare it for binary search.

4. Display sorted roll numbers: Display the sorted list of roll numbers.

5. Input roll number to search: Read the roll number x that the user wants to search for.

6. Binary search:

• Initialize two pointers, low (set to 0) and high (set to num - 1).

• While low is less than or equal to high:

o Calculate the middle index mid using the formula: mid = low + (high - low) / 2.
o If Arr[mid] is equal to x, print that the roll number is found and its position (index mid)
and terminate the search.
o If Arr[mid] is less than x, move the low pointer to mid + 1 (search in the right half).
o If Arr[mid] is greater than x, move the high pointer to mid - 1 (search in the left half).

• If the loop ends without finding x, print that the roll number is not found.

7. End.

1|Page
Output:

2|Page
PROGRAM:

#include<iostream>

using namespace std;

int main()

cout<<"URN:2203415\n\n";

cout<<"Binary Search\n";

int arr[5]={5,6,8,9,10};

int lower=0,upper=4,found=0,mid,item;

cout<<"Enter the Roll No. to find the position:";

cin>>item;

while(lower<=upper)

mid=(lower+upper)/2;

if(arr[mid]==item)

found=1;

break;

if(arr[mid]<item)

lower=mid+1;

else

upper=mid-1;

3|Page
4|Page
}

if(found==1)

cout<<"Roll No. is found in index:"<<mid;

else

cout<<"Roll No. is not found";

5|Page
6|Page
PRACTICAL NO. 2
Write a program to sort the class roll numbers of your class using merge sort
algorithm and determine the time required to sort the elements.
Merge Sort is an efficient, stable, and comparison-based sorting algorithm with a time complexity
of O(nlogn) for both the average and worst-case scenarios. It is particularly useful for sorting large
datasets due to its predictable time complexity and stable sort properties.

ALGORITHM: The algorithm for the given program is given below, from where we easily get
to know about how this particular program will work.

1. Initialization:

 Define the maximum array size and create an array to store roll numbers.

2. Input Handling:

 Prompt the user to enter the number of roll numbers.


 Check if the number of roll numbers is within valid limits.
 Input roll numbers into the array.

3. Sorting:

 Start the timer.


 Call the mergeSort function to sort the array.
 End the timer.

4. Merge Sort:

 Merge Function:
Input: A sorted left half and a sorted right half of the array.
Process:
o Create temporary arrays to hold the left and right halves.
o Copy the data from the original array to the temporary arrays.
o Merge the two temporary arrays back into the original array in sorted order

Output: A combined sorted array from the two halves.

 Merge Sort Function:

Input: The array to be sorted, and the indices of the subarray (left and right).

Process:

7|Page
Output:

8|Page
o Find the middle index of the array.
o Recursively sort the left half.
o Recursively sort the right half.
o Merge the sorted halves using the merge function.

Output: A sorted array.

5. Output:

 Display the sorted roll numbers.


 Display the time taken to sort the array.

PROGRAM:

#include <iostream>

#include <vector>

#include <ctime>

using namespace std;

// Function to perform merge sort

void mergeSort(vector<int>& arr) {

if (arr.size() > 1) {

int mid = arr.size() / 2;

// Divide the array into two halves

vector<int> L(arr.begin(), arr.begin() + mid);

vector<int> R(arr.begin() + mid, arr.end());

// Sort the two halves

mergeSort(L);

mergeSort(R);

// Merge the sorted halves

int i = 0, j = 0, k =

0;

while (i < L.size() && j < R.size()) {


9|Page
10 | P a g e
if (L[i] < R[j]) {

arr[k++] = L[i++];

} else {

arr[k++] = R[j++];

// Copy any remaining elements of L

while (i < L.size()) {

arr[k++] = L[i++];

// Copy any remaining elements of R

while (j < R.size()) {

arr[k++] = R[j++];

// Function to print the list

void printList(const vector<int>& arr) {

for (int i = 0; i < arr.size(); i++) {

cout << arr[i] << " ";

cout << endl;

// Driver code to test the above code

int main() {

cout<<"URN:2203415\n";

clock_t start_time = clock();

11 | P a g e
12 | P a g e
vector<int> arr = {1715080, 1715073, 1715072, 1715082, 1715062, 1715022};

cout << "\nEntered Roll numbers are: " <<endl;

printList(arr);

mergeSort(arr);

cout << "\nSorted array is: " << endl;

printList(arr);

cout<<"\nTime required to sort the elements:\n";

cout << "It took " << double(clock() - start_time) / CLOCKS_PER_SEC << " seconds to
execute." << endl;

return 0;

13 | P a g e
14 | P a g e
PRACTICAL NO. 3
Write a program to sort the university roll numbers of your class using Quick
sort method and determine the time required to sort the elements.
Quick Sort is an efficient, comparison-based sorting algorithm with an average time complexity
of O(n log n). It uses a divide-and-conquer approach and is often faster than Merge Sort for smaller
datasets. However, it is not stable and can degrade to O(n²) in the worst case, typically mitigated
by strategies like random pivot selection.

ALGORITHM:

1. Initialization:
 Define the maximum array size and create an array to store roll numbers.
2. Input Handling:
 Prompt the user to enter the number of roll numbers.
 Check if the number of roll numbers is within valid limits.
 Input roll numbers into the array.
3. Sorting:
 Start the timer.
 Call the quickSort function to sort the array.
 End the timer.
4. Quick Sort:
 Partition Function:
o Input: The array to be sorted, and the indices of the subarray (low and
high).
o Process:
 Choose the last element as the pivot.
 Rearrange elements so that elements less than the pivot are on the
left and elements greater than the pivot are on the right.
 Place the pivot in its correct position. o
o Output: The index of the pivot after rearranging.
 Quick Sort Function:
o Input: The array to be sorted, and the indices of the subarray (low and
high).
o Process:
 If the subarray has more than one element, partition it using the
partition function.
 Recursively apply quick sort to the left and right subarrays.
o Output: A sorted array.
5. Output: • Display the sorted roll numbers. • Display the time taken to sort the array.

15 | P a g e
Output:

16 | P a g e
PROGRAM:

#include <iostream>

#include <vector>

#include <ctime>

using namespace std;

// Function to partition the array

int partition(vector<int>& arr, int low, int high) {

int pivot = arr[high]; // pivot

int i = low - 1; // index of smaller element

for (int j = low; j < high; j++) {

// If current element is smaller than the pivot

if (arr[j] < pivot) {

i++; // increment index of smaller element

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

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

return i + 1;

// The main function that implements QuickSort

void quickSort(vector<int>& arr, int low, int high) {

if (low < high) {

// pi is partitioning index, arr[pi] is now at right place

int pi = partition(arr, low, high);

// Separately sort elements before and after partition

17 | P a g e
18 | P a g e
quickSort(arr, low, pi - 1);

quickSort(arr, pi + 1, high); }

// Driver code to test the above functions

int main() {

cout<<"URN:2203415";

clock_t start_time = clock();

vector<int> arr = {202101, 202105, 202103, 202104, 202102};

int n = arr.size();

cout << "\n\nRoll Nos. provided initially: " << endl;

for (int i = 0; i < n; i++) {

cout << arr[i] << " ";

cout << endl;

quickSort(arr, 0, n - 1);

cout << "\nSorted array is: " << endl;

for (int i = 0; i < n; i++) {

cout << arr[i] << " ";

cout << endl;

cout<<"\nTime required to sort the elements:";

cout << "\nIt took " << double(clock() - start_time) / CLOCKS_PER_SEC << " seconds to
execute" << endl;

return 0;

19 | P a g e
20 | P a g e
PRACTICAL NO. 4
Write a program to solve 0/1 knapsack using Greedy algorithm.
The 0/1 Knapsack problem involves selecting items with given weights and values to maximize
the total value without exceeding a weight limit. While the Greedy algorithm is typically used for
the Fractional Knapsack problem, it can be adapted for the 0/1 Knapsack, though it may not
always yield an optimal solution.

ALGORITHM:

1. Initialization:
o Define the maximum weight capacity of the knapsack W.
o Create a list of items, each with a specific weight and value.
2. Input Handling:
o Calculate the value-to-weight ratio for each item.
3. Sorting:
o Sort the items in descending order based on their value-to-weight ratio
4. Greedy Approach:
o Initialize totalValue to 0 and currentWeight to 0.
o Iterate through the sorted items:
 If the current item's weight can be added without exceeding W, add it to
the knapsack.
 Update currentWeight and totalValue accordingly.
5. Output:
o Return the total value of the items in the knapsack as the solution.

21 | P a g e
Output:

22 | P a g e
PROGRAM:

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

struct Item

int weight;

int value;

double valuePerWeight;

};

bool compare(Item a, Item b)

return a.valuePerWeight > b.valuePerWeight;

int knapsackGreedy(int W, vector<Item>& items)

sort(items.begin(), items.end(), compare);

int totalValue = 0;

int currentWeight = 0;

for (const auto& item : items)

if (currentWeight + item.weight <= W)

currentWeight += item.weight;

23 | P a g e
24 | P a g e
totalValue += item.value;

return totalValue;

int main()

int W = 50;

cout<<"URN: 2203415\n\n";

vector<Item> items = {{10, 40}, {20, 60}, {30, 80}};

for (auto& item : items)

item.valuePerWeight = (double)item.value / item.weight;

int maxValue = knapsackGreedy(W, items);

cout << "Maximum value in Knapsack:" << maxValue << endl;

return 0;

25 | P a g e
26 | P a g e
PRACTICAL NO. 5
Write a program to find minimum cost to set the phone lines to connect all the
cities of your state using Prim's algorithm.
Prim's Algorithm is an efficient method to find the Minimum Spanning Tree (MST) of a
weighted graph, ensuring all cities (vertices) are connected with the minimum total cost. It
incrementally builds the MST by adding the least costly edges while avoiding cycles.

ALGORITHM:

1. Initialization:
 Create a matrix graph[V][V] representing the costs of connecting cities.
 Initialize an array key[] to store the minimum edge weights, initially set to
infinity.
 Initialize a boolean array mstSet[] to track vertices included in the MST, initially
set to false.
 Initialize an array parent[] to store the constructed MST, with all entries initially
set to -1.
2. Prim's MST Construction:
 Set key[0] = 0, making the first vertex the starting point.
 For V-1 times:
o Select the vertex u with the minimum key value that is not yet included in
the MST.
o Include u in the MST by setting mstSet[u] = true.
o For each vertex v adjacent to u:
 If v is not in the MST and the cost of the edge u-v is less
than key[v], update key[v] and set parent[v] = u.
3. Output:
 Print the edges and their weights included in the MST.
 Calculate and display the total minimum cost to connect all cities.

27 | P a g e
Output:

28 | P a g e
PROGRAM:

#include <iostream>

#include <vector>

#include <climits>

using namespace std;

int main() {

cout<<"URN:2203415\n\n";

const int INF = INT_MAX;

int src = 0;

// Adjacency matrix representing the graph

int weight[9][9] = {

{INF, 4, INF, INF, INF, INF, INF, 8, INF},

{4, INF, 8, INF, INF, INF, INF, 11, INF},

{INF, 8, INF, 7, INF, 4, INF, INF, 2},

{INF, INF, 7, INF, 9, 14, INF, INF, INF},

{INF, INF, INF, 9, INF, 10, INF, INF, INF},

{INF, INF, 4, 14, 10, INF, 2, INF, INF},

{INF, INF, INF, INF, INF, 2, INF, 1, 6},

{8, 11, INF, INF, INF, INF, 1, INF, 7},

{INF, INF, 2, INF, INF, INF, 6, 7, INF}

};

// Initialization

vector<bool> visited(9, false);

vector<int> distance(9, INF);

vector<int> nbr(9, -1);

29 | P a g e
30 | P a g e
visited[src] = true;

for (int j = 0; j < 9; j++)

{ nbr[j] = 0;

distance[j] = weight[0][j];

vector<pair<int, int>> edges;

for (int i = 1; i < 9; i++) {

int min = INF;

int index = -1;

// Find the unvisited node with the minimum distance

for (int j = 0; j < 9; j++) {

if (!visited[j] && distance[j] < min) {

index = j;

min = distance[j];

if (index == -1) {

break; // All nodes are visited or the remaining nodes are not connected

edges.push_back({nbr[index], index});

visited[index] = true;

// Update the distance and nbr arrays

for (int k = 0; k < 9; k++) {

if (!visited[k] && distance[k] > weight[index][k]) {

distance[k] = weight[index][k];

31 | P a g e
32 | P a g e
nbr[k] = index;

// Print the result

cout << "Path selected for phone lines [city1 -> city2] \t\t Cost" << endl;

for (int i = 0; i < 8; i++) {

cout << "[" << edges[i].first << " -> " << edges[i].second << "]"

<< "\t\t\t\t\t\t\t " << distance[edges[i].second] << endl;

int total_cost = 0;

for (int i = 1; i < 9; i++) {

total_cost += distance[i];

cout << "Minimum cost of connecting all cities through phone line is: " << total_cost << endl;

return 0;

INPUT GRAPH:

33 | P a g e
34 | P a g e
PRACTICAL NO. 6
Write a program to find the minimum cost of connecting all the engineering
colleges in your state using Kruskal's algorithm.
Kruskal's Algorithm is a greedy approach to finding the Minimum Spanning Tree (MST) of a
graph, which helps connect all engineering colleges (vertices) with the minimum total cost. It
works by sorting all edges by weight and adding them to the MST while avoiding cycles,
ensuring the lowest possible connection cost.

ALGORITHM:

1. Initialization:
 Create a list of all edges in the graph, where each edge connects two vertices
(colleges) with a given cost.
 Sort the edges in non-decreasing order of their weights.
 Initialize a parent array and rank array for the Union-Find data structure to
manage the disjoint sets.
2. Kruskal's MST Construction:
 Iterate through the sorted edges:
 For each edge, use the find operation to check if the source and
destination vertices are in different sets.
 If they are in different sets, add the edge to the MST and unite the
sets using the union operation.
 Continue until the MST contains exactly V-1 edges, where V is the
number of vertices (colleges).
3. Output:
 Print the edges included in the MST.
 Display the total minimum cost to connect all colleges.

35 | P a g e
Output:

36 | P a g e
PROGRAM:

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

// Class to represent a graph

class Graph {

int V; // No. of vertices

vector<vector<int>> graph; // Graph to store edges as {u, v, w}

public:

Graph(int vertices) {

V = vertices;

// Function to add an edge to the graph

void addEdge(int u, int v, int w) {

graph.push_back({u, v, w});

// A utility function to find set of an element i (uses path compression technique)

int find(vector<int>& parent, int i) {

if (parent[i] == i)

return i;

return parent[i] = find(parent, parent[i]);

// A function that does union of two sets of x and y (uses union by rank)

void unionSets(vector<int>& parent, vector<int>& rank, int x, int y) {

int xroot = find(parent, x);

int yroot = find(parent, y);

37 | P a g e
38 | P a g e
// Attach smaller rank tree under root of high rank tree (Union by Rank)

if (rank[xroot] < rank[yroot]) {

parent[xroot] = yroot;

} else if (rank[xroot] > rank[yroot]) {

parent[yroot] = xroot;

} else {

parent[yroot] = xroot;

rank[xroot] += 1;

// The main function to construct MST using Kruskal's algorithm

void KruskalMST() {

vector<vector<int>> result; // Store the resultant MST

int i = 0; // Index variable for sorted edges

int e = 0; // Index variable for result[]

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

sort(graph.begin(), graph.end(), [](const vector<int>& a, const vector<int>& b) {

return a[2] < b[2];

});

vector<int> parent(V), rank(V, 0);

// Create V subsets with single elements

for (int node = 0; node < V; ++node) {

parent[node] = node;

// Number of edges to be taken is equal to V-1

while (e < V - 1) {

// Step 2: Pick the smallest edge and increment the index for next iteration

39 | P a g e
40 | P a g e
int u = graph[i][0];

int v = graph[i][1];

int w = graph[i]

[2]; i++;

int x = find(parent, u);

int y = find(parent, v);

// If including this edge doesn't cause a cycle, include it in result

if (x != y) {

result.push_back({u, v, w});

e++;

unionSets(parent, rank, x, y);

// Print the contents of result[] to display the built MST

cout << "Following are the edges in the constructed MST\n";

for (const auto& edge : result) {

cout << edge[0] << " -- " << edge[1] << " == " << edge[2] << endl;

};

// Driver code

int main() {

cout<<"URN:2203415\n\n";

Graph g(4);

g.addEdge(0, 1, 10);

g.addEdge(0, 2, 6);

g.addEdge(0, 3, 5);

41 | P a g e
42 | P a g e
g.addEdge(1, 3, 15);

g.addEdge(2, 3, 4);

g.KruskalMST();

return 0;

43 | P a g e
44 | P a g e
PRACTICAL NO. 7
Write a program to find minimum route for a newspaper distributer of
your locality using Greedy algorithm.
The Nearest Neighbor Algorithm, a Greedy approach, is used to find an approximate minimum
route for a newspaper distributor. This method selects the closest unvisited house at each step,
aiming to minimize the total distance traveled.

ALGORITHM:

1. Initialization:
 Define a list of houses with their coordinates.
 Initialize a boolean array visited[] to keep track of visited houses.
 Start from the first house and mark it as visited.
2. Greedy Route Selection:
 For each house, find the nearest unvisited house using the distance formula.
 Move to the nearest house, mark it as visited, and add the distance to the total
distance.
 Continue until all houses are visited.
3. Return to Start:
 After visiting all houses, return to the starting house to complete the route.
4. Output:
 Print the route taken and the total distance covered.

45 | P a g e
Output:

46 | P a g e
PROGRAM:

#include <iostream>

#include <vector>

#include <climits>

using namespace std;

class Graph {

public:

int minDistance(vector<int>& dist, vector<bool>& sptSet) {

int min = INT_MAX, min_index;

for (int v = 0; v < dist.size(); v++)

if (!sptSet[v] && dist[v] <= min)

min = dist[v], min_index = v;

return min_index;

void printPath(vector<int>& parent, int j) {

if (parent[j] == -1)

return;

printPath(parent, parent[j]);

cout << j << " ";

void printSolution(vector<int>& dist, vector<int>& parent) {

int src = 0;

cout << "Vertex\t\tDistance\tPath" << endl;

for (int i = 1; i < dist.size(); i++) {

cout << src << " -> " << i << "\t\t" << dist[i] << "\t\t\t" << src << " ";

printPath(parent, i);

cout << endl;

47 | P a g e
48 | P a g e
}

void dijkstra(vector<vector<int>>& graph, int src) {

int V = graph.size();

vector<int> dist(V, INT_MAX);

vector<bool> sptSet(V, false);

vector<int> parent(V, -1);

dist[src] = 0;

for (int count = 0; count < V - 1; count++)

{ int u = minDistance(dist, sptSet);

sptSet[u] = true;

for (int v = 0; v < V; v++)

if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] <
dist[v]) {

parent[v] = u;

dist[v] = dist[u] + graph[u][v];

printSolution(dist, parent);

};

int main() {

cout<<"URN:2203415\n\n";

Graph g;

vector<vector<int>> graph = {

{0, 4, 0, 0, 0, 0, 0, 8, 0},

{4, 0, 8, 0, 0, 0, 0, 11, 0},

{0, 8, 0, 7, 0, 4, 0, 0, 2},

49 | P a g e
50 | P a g e
{0, 0, 7, 0, 9, 14, 0, 0, 0},

{0, 0, 0, 9, 0, 10, 0, 0, 0},

{0, 0, 4, 14, 10, 0, 2, 0, 0},

{0, 0, 0, 0, 0, 2, 0, 1, 6},

{8, 11, 0, 0, 0, 0, 1, 0, 7},

{0, 0, 2, 0, 0, 0, 6, 7, 0}

};

g.dijkstra(graph, 0);

return 0;

51 | P a g e
52 | P a g e
PRACTICAL NO. 8
Write a program to find shortest path from your home to college using
Dijkstra’s algorithm.
Dijkstra's algorithm is a popular and efficient method for finding the shortest path between nodes
in a graph, particularly in weighted graphs. It's widely used in various real-world applications
like GPS navigation and network routing to determine the most efficient path.

ALGORITHM:

1. Initialization:
o Create an adjacency matrix graph[V][V] to represent distances between locations.
o Initialize an array dist[] with INT_MAX for all locations, except the starting
location (home), which is set to 0.
o Initialize a visited[] array to keep track of the visited vertices.
2. Dijkstra’s Algorithm:
o For each vertex, find the unvisited vertex with the minimum distance from the
source.
o Mark this vertex as visited.
o Update the distance for all adjacent vertices of the selected vertex. If a shorter
path is found, update the distance.
3. Output:
o Print the shortest distances from the home to all other locations, including the
college.

53 | P a g e
Output:

54 | P a g e
PROGRAM:

#include <iostream>

#include <vector>

#include <climits>

using namespace std;

int findMinDistanceVertex(vector<int>& dist, vector<bool>& visited, int V)

int minDist = INT_MAX;

int minIndex = -1;

for (int v = 0; v < V; v++)

if (!visited[v] && dist[v] < minDist)

minDist = dist[v];

minIndex = v;

return minIndex;

void dijkstra(vector<vector<int>>& graph, int src, int V)

vector<int> dist(V, INT_MAX);

vector<bool> visited(V, false);

dist[src] = 0;

for (int count = 0; count < V - 1; count++)

55 | P a g e
56 | P a g e
{

int u = findMinDistanceVertex(dist, visited, V);

visited[u] = true;

for (int v = 0; v < V; v++)

if (!visited[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v])

dist[v] = dist[u] + graph[u][v];

cout << "Location \t Distance from Home\n";

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

cout << i << " \t\t\t " << dist[i] << endl;

cout << "\nShortest distance from Home to College: " << dist[V-1];

int main()

int V = 5;

vector<vector<int>> graph =

{0, 10, 0, 30, 100},

{10, 0, 50, 0, 0},

57 | P a g e
58 | P a g e
{0, 50, 0, 20, 10},

{30, 0, 20, 0, 60},

{100, 0, 10, 60, 0} // Distances from college (index 4)

};

int home = 0;

cout<<"URN: 2203415\n\n";

dijkstra(graph, home, V);

return 0;

59 | P a g e

You might also like