Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

Name: Nazim Firdous Ali

BSCS 6C
Registration# 1612202
Assignment# 1
Q1: Implement the code for inline quick sort algorithm and sort the following data: [2 8 7
1 3 5 6 4]

A1:

namespace ConsoleApp1Assignmentq3
{
classProgram
{
privatestaticvoid QS(int[] a, intleft, intright)
{
if (left < right)
{
intpivot = Partition(a, left, right);

if (pivot > 1)
{
QS(a, left, pivot - 1); //If the pivot is greater
then 1 then pivot-1
}
if (pivot + 1 < right)
{
QS(a, pivot + 1, right);
}
}

privatestaticintPartition(int[] a, intleft, intright)


{
intpivot = a[left];
while (true)
{

while (a[left] < pivot)


{
left++; //If the left value of array is les then pivot
then left++
}

while (a[right] > pivot)


{
right--; //If the left value of array is Greater then
pivot then left--
}

if (left<right)
{
if (a[left]==a[right])returnright;

inttemp=a[left]; //Rearrangement
a[left]=a[right];
a[right]=temp;

}
else
{
returnright;
}
}
}
staticvoidMain(string[] args)
{
int[] a = new int[] { 9,6,2,1,4,2,7,5 }; //Hard code value

Console.WriteLine("Array Before Sorting : ");


foreach (var item in a)
{
Console.Write(" " +item);
}
Console.WriteLine();

QS(a, 0, a.Length - 1);

Console.WriteLine();
Console.WriteLine("Array After Sorting : ");

foreach (var item in a)


{
Console.Write(" " + item);
}
Console.WriteLine();
Console.ReadLine();
}
}
}
Q2: Identify all formats for graph representation and storage (at least one other than the
two taught in course). Implement Adjacency list method. Show output for a 4 vertex
graph in which each vertex is connected to other (use linked list already provided by the
language).

A2:
 Adjacency List:
An array of lists is used. Size of the array is equal to the no of vertices. Let the array be
array[]. An entry array[i] represents the list of vertices adjacent to the ith vertex.

 Adjacency Matrix:
Adjacency Matrix is a 2D array of size V x V where V is the number of vertices in a
graph. Let the 2D array be adj[][], a slot adj[i][j] = 1 indicates that there is an edge from
vertex i to vertex j.
 Adjacency Array:
Similar to an adjacency list, an adjacency array keeps the neighbors of all vertices, one
after another, in an array adj; and separately, keeps an array of indices that tell us where
in the adj array to look for the neighbors of each vertex.

 Adjacency Tables:
To more efficiently access neighbors we will use adjacency tables, which are a
generalization of adjacency lists and adjacency arrays. The adjacency table
representation is a table that maps every vertex to the set of its (out) neighbors.

 Adjacency Sequences:
A special case of adjacency tables are adjacency sequences. remember that a
sequence is a table with a domain taken from {0, . . . , n − 1}.

 Edge List:
To represent an edge, we just have an array of two vertex numbers, or an array of
objects having the vertex # of the vertices that the edges are incident on. If edges have
weights, add either a third element to the array or more info to the object, giving the
edge's weight. 

Implement Adjacency list method:


Program.cs:

namespace ConsoleApp2Q4
{
class Program
{
staticvoidMain(string[] args)
{
Console.WriteLine("Total Vertices: ");
inta = int.Parse(Console.ReadLine());

aList adjancyList = new aList(a + 1);


Console.WriteLine(" Total edges: ");
intb = int.Parse(Console.ReadLine());

Console.WriteLine(" Total weight of edges: ");


int s, v, w;
for (int c = 0; c < b; ++c)
{
s = int.Parse(Console.ReadLine());
v = int.Parse(Console.ReadLine());
w = int.Parse(Console.ReadLine());
adjancyList.add_Edge_end(s, v, w);
}
adjancyList.print_AdjancyList();
Console.ReadLine();
}
}
}

List.cs //New file:

namespace ConsoleApp2Q4
{
classaList
{
LinkedList<Tuple<int, int>>[] adj_list;

publicaList(intd)
{
adj_list=newLinkedList<Tuple<int,int>>[d];
for (inte = 0; e < adj_list.Length; ++e)
{
adj_list[e]=newLinkedList<Tuple<int, int>>();
}
}
publicvoidadd_Edge_end(ints, intv,intw)
{
adj_list[s].AddLast(newTuple<int,int>(v, w));
}
publicvoidadd_Edge_start(ints, int v,intw)
{
adj_list[s].AddFirst(newTuple<int,int>(v, w));
}
publicint total_vertices()
{
returnadj_list.Length;
}
publicLinkedList<Tuple<int,int>>this[intind]
{
get
{
LinkedList<Tuple<int, int>> edge_List = newLinkedList<Tuple<int,
int>>(adj_list[ind]);
returnedge_List;
}
}
publicvoidprint_AdjancyList()
{
int f = 0;
foreach (LinkedList<Tuple<int, int>> l in adj_list)
{
Console.WriteLine("adjacency list is: [" + f + "]");
foreach (Tuple<int, int> EdG in l)
{
Console.WriteLine(EdG.Item1 + "(" + EdG.Item2 + ")");
}
++f;
Console.WriteLine();
}
}
publicbooldelete_edge(int s, int v, int w)
{
Tuple<int,int>g=new Tuple<int, int>(v, w);
returnadj_list[v].Remove(g);
}

}
}

Q3 : Implement the coin-changing problem using your favorite programming language


for Pakistani currency (Use single rupee as minimum denomination). Run the program
for Rs. 1988 and display each denomination currency required.

A3:

namespace ConsoleApp1AssignmentHussnain
{
class Program
{
staticvoidMain(string[] args)
{
int[]Ruppess = { 5000, 1000, 500, 100, 50, 20, 10, 5, 2, 1 }; //Taking pak
currency
intamount, number, i; //initialize
Console.Write("Enter the amount you want to change : ");
amount = Convert.ToInt32(Console.ReadLine()); //Taking input
for (i = 0; i < Ruppess.Length; i++) //loop till the length of array
{
number = amount / Ruppess[i]; //divide the total number by the ruppees
if (number != 0) //run till input in not equal to 0
Console.WriteLine("Number of {0} Ruppess :{1}", Ruppess[i], number);
amount %= Ruppess[i];
}

Console.ReadLine();

Q4: Write the pseudo-code for compression and decompression routines of Huffman
Coding. Show the encoding and decoding of the following sample text: “Time complexity
of Huffman Coding is O(n log n)”.
def frequency(s):

weight={}

for char in s :

weight[char] = weight.get(char,0) + 1
return weight

class Fork:

def __init__(self,chars, weight,left=None, right=None,):

self.left = left

self.right = right

self.chars = chars

self.weight = weight

defsort_frq (weight) :

symbols = weight.keys()

tuples = []

for e in symbols :

tuples.append((weight[e],e))

tuples.sort()

return tuples

defmake_code_table(codeTree):

codList=basecodetable(codeTree)

codList0={}

for (k,v) in codList:

codList0[k]=v

return(codList0)

defcreateCodeTree(sample):

nodes=sorted([Fork(k,v) for (k,v) in frequency(sample).items()],key=lambda


x:x.weight)

while len(nodes) > 1:

nodes=sorted(([Fork(nodes[0].chars+nodes[1].chars,nodes[0].weight+nodes[1].weight,nodes[0
],nodes[1])]+nodes[2:]),key=lambda x:x.weight)

return(nodes[0])

def encode(string,tree):

returnbaseencode(string,tree,tree,"")
defbaseencode(s,node,tree,rslt):

if s=='':

returnrslt

elifnode.left==None:

returnbaseencode(s[1:],tree,tree,rslt)

elif s[0] in node.left.chars:

returnbaseencode(s,node.left,tree,rslt+'0')

else:

returnbaseencode(s,node.right,tree,rslt+'1')

def decode(string,tree):

return(basedecode(string,tree,tree,""))

defbasedecode(s,node,tree,rslt):

if s=="":

return(rslt+node.chars)

elifnode.left==None:

return(basedecode(s,tree,tree,rslt+node.chars))

elif s[0]=='0':

return(basedecode(s[1:],node.left,tree,rslt))

else:

return(basedecode(s[1:],node.right,tree,rslt))

defbasecodetable(tree):

iftree.left == None :

return [(tree.chars,'')]

x=basecodetable(tree.right)

y=basecodetable(tree.left)

return [(i,'0'+j) for (i,j) in y]+[(i,'1'+j) for (i,j) in x]

defquickEncode(string,codList):
rslt=""

for i in string:

rslt=rslt+codList[i]

returnrslt

class Leaf:

def __init__(self, chars, weight):

self.left = None

self.right = None

self.chars = chars

self.weight = weight

def test():

print ('\nType Any String:')

n = input("\n")

tree=createCodeTree((n))

table=make_code_table(tree)

print ("code table:" ,table)

print ('string: ' +str(n))

print ('Encode: ')

print (encode(n,tree))

a = (encode(n,tree))

print ('Decode string: ',)

print (decode(a,tree))

test()

You might also like