CSE2012 Lab Assignment 1
CSE2012 Lab Assignment 1
Lab Assessment-1
Pseudo code:
1. Declare left and right var which will mark the extreme indices of the array
2. Left will be assigned to 0 and right will be assigned to n-1
3. Find mid = (left+right)/2
4. Above will continue till left<right
5. Then we will call merge on the 2 sub problems
Algorithm:
Mergersort(arr,left,right):
If left>right
Return
Mid=(left+right)/2
Mergesort(arr,left,mid)
Mergersort(arr,mid+1,RIGHT)
Mergesort(arr,left,mid,right); end
Code:
#include <stdlib.h>
#include <stdio.h>
i = 0; j = 0; k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
int main()
{
int a[20], s, i, j, n, key;
printf("Enter array size: ");
scanf("%d", &s);
printf("Enter array to sort: ");
for (i = 0; i < s; i++)
scanf("%d", &a[i]);
mergeSort(a, 0, s - 1);
printf("\nSorted array: ");
for (i = 0; i < s; i++)
printf("%d ", a[i]);
return 0;
}
Input & Output:
Complexity Analysis:
Time complexity analysis:
In the merge() function it iterates over a array and the arrays can have at most size of n.
Rest of the process we are just comparing and assigning values and they are constant time
process. Thus merge() has a running time of O(n).
Now for the mergesort() function, it is breaking the problem size of n into two
subproblems of size n/2 each. The comparision and calculation in the middle are
constant time taking process. So the time complexity of merge-sort algorithm will be:
Space complexity analysis:
In the merge phase, elements from two subarrays are copied into a new array. In the
last step, the new array is exactly as large as the array to be sorted. Thus we have a
linear requirement.
The space complexity of Merge Sort is O(n)
Result:
Aim: To Write A Program for Huffman Coding with proper Algorithm and Flowchart.
Problem Analysis: Huffman coding is a greedy algorithm which is used for lossless
compression of data. It reduces the number of bits without removing the data. The
algorithm is based on frequency of the characters appearing in a file. Our computer stores
our files as binary code and each character has a binary character and this characters are of
fixed length.
Here in Huffman coding it doesn’t use fixed length for each character it assigns the length
based on the frequency! It assigns a short length for the character that comes more time!
Since characters which have high frequency has lower length, they take less space and save
the space required to store the file.
Huffman (C)
-> n=|C|
-> Q ← C
-> for i=1 to n-1
-> do
-> z= allocate-Node ()
-> x= left[z]=Extract-Min(Q)
-> y= right[z] =Extract-Min(Q)
-> f [z]=f[x]+f[y]
-> Insert (Q, z)
->return Extract-Min (Q)
4. Remove the two trees from the forest that have the lowest count contained in their roots.
5. Create a new node that will be the root of a new tree. This new tree will have those two
trees just removed in step 2a as left and right subtrees. The count in the root of this new
tree will be the sum of the counts in the roots of its subtrees. Label the edge from this new
root to its left subtree “1”, and label the edge to its right subtree “0”.
7. Return the one tree in the forest as the Huffman code tree.
Flowchart:
Code:
#include <iostream>
using namespace std;
#define MAX 50
struct MinHNode
{
unsigned freq;
char item;
struct MinHNode *left, *right;
};
struct MinH
{
unsigned size;
unsigned capacity;
struct MinHNode **array;
};
return temp;
}
if (smallest != idx)
{
swap(&minHeap->array[smallest], &minHeap->array[idx]);
minHeapify(minHeap, smallest);
}
}
--minHeap->size;
minHeapify(minHeap, 0);
return temp;
}
minHeap->size = size;
buildMinHeap(minHeap);
return minHeap;
}
while (minHeap->size != 1)
{
left = extractMin(minHeap);
right = extractMin(minHeap);
top->left = left;
top->right = right;
insertMinHeap(minHeap, top);
}
return extractMin(minHeap);
}
if (root->right)
{
a[top] = 1;
printHuffmanCodes(root->right, a, top + 1);
}
if (isLeaf(root))
{
cout << root->item << " --> ";
for (int i = 0; i < top; ++i)
cout << a[i];
cout << endl;
}
}
int main()
{
char a[] = {'R', 'B', 'C', 'S', 'A', 'Z'};
int freq[] = {9, 7, 16, 32, 1, 42};
Result: Hence, we have proved Huffman coding with greedy Algorithm! We have succefully
have compressed the data with removing any data.
3. Backtracking – N Queens Problem
Aim: Place n-queens in N*N chess board so that no of them can attack i.e. no of them are on
the same row, column or diagonal!
Problem Analysis:
We Use Backtracking to solve this N Queens Problem. You are given an 8x8 chessboard, find
a way to place 8 queens such that no queen can attack any other queen on the chessboard.
A queen can only be attacked if it lies on the same row, or same column, or the same
diagonal of any other queen. Print all the possible configurations.
To solve this problem, we will make use of the Backtracking algorithm. The backtracking
algorithm, in general checks all possible configurations and test whether the required result
is obtained or not. For thr given problem, we will explore all possible positions the queens
can be relatively placed at. The solution will be correct when the number of placed queens =
8.
Backtracking happens for either of two reasons:
#define N 5
#include <stdbool.h>
#include <stdio.h>
return true;
}
board[i][col] = 0;
}
}
return false;
}
bool solveNQ()
{
int board[N][N] = {{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0}};
if (solveNQUtil(board, 0) == false)
{
printf("Solution does not exist");
return false;
}
int main()
{
solveNQ();
return 0;
}
Result:
Time complexity: O(n!)
Space complexity: O(n*n)
We Have placed n-qeens N * N chess board so that no of them can attack i.e. no of them are
on the same row, column or diagonal! Using backtracking!
Complexity Analysis Table:
1.The sum of i and j is constant and unique for each right diagonal where i is the row of
element and j is the
column of element.
2.The difference of i and j is constant and unique for each left diagonal where i and j are row
and column of element respectively.
Code:
#include <stdbool.h>
#include <stdio.h>
#define N 5
int r_diag[N] = { 0 };
int l_diag[N] = { 0 };
int cl[N*N] = { 0 };
board[i][col] = 0;
l_diag[i - col + N - 1] = r_diag[i + col] = cl[i] = 0;
}
return false;
}
void solveNQ()
{
int board[N][N] = { { 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0 } };
if (solveNQUtil(board, 0))
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
printf(" %d ", board[i][j]);
printf("\n");
}
else printf("Solution does not exist");
}
int main()
{
solveNQ();
return 0;
}
Input and Output: