deepalipawar.files.wordpress.com€¦  · web viewaddition operation traverses the matrices...

24
1a.Define algorithms & its Characteristics

Upload: others

Post on 12-Aug-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: deepalipawar.files.wordpress.com€¦  · Web viewAddition operation traverses the matrices linearly, hence, has a time complexity of O(n), where n is the number of non-zero elements

1a.Define algorithms & its Characteristics

Page 2: deepalipawar.files.wordpress.com€¦  · Web viewAddition operation traverses the matrices linearly, hence, has a time complexity of O(n), where n is the number of non-zero elements

1.b.Write Pseudo C/C++ code to perform simple traspose of sparse matrix.Discuss it's time complexity.

public sparse_matrix transpose()     {           // new matrix with inversed row X col         sparse_matrix result = new sparse_matrix(col, row);           // same number of elements         result.len = len;           // to count number of elements in each column         int count[] = new int[col + 1];           // initialize all to 0         for (int i = 1; i <= col; i++)             count[i] = 0;           for (int i = 0; i < len; i++)             count[data[i][1]]++;           int[] index = new int[col + 1];           // to count number of elements having col smaller         // than particular i           // as there is no col with value < 1         index[1] = 0;           // initialize rest of the indices         for (int i = 2; i <= col; i++)               index[i] = index[i - 1] + count[i - 1];           for (int i = 0; i < len; i++) {               // insert a data at rpos and increment its value             int rpos = index[data[i][1]]++;               // transpose row=col             result.data[rpos][0] = data[i][1];               // transpose col=row             result.data[rpos][1] = data[i][0];               // same value             result.data[rpos][2] = data[i][2];         }           // the above method ensures         // sorting of transpose matrix         // according to row-col value         return result;     }

Page 3: deepalipawar.files.wordpress.com€¦  · Web viewAddition operation traverses the matrices linearly, hence, has a time complexity of O(n), where n is the number of non-zero elements

Addition operation traverses the matrices linearly, hence, has a time complexity of O(n), where n is the number of non-zero elements in the larger matrix amongst the two. Transpose has a time complexity of O(n+m), where n is the number of columns and m is the number of non-zero elements in the matrix. Multiplication, however, has a time complexity of O(x*n + y*m), where (x, m) is number of columns and terms in the second matrix; and (y, n) is number of rows and terms in the first matrix.

1.c.Drive address calculation formula for one dimensional array with one example

Address Calculation in single (one) Dimension Array:

Array of an element of an array say “A[ I ]” is calculated using the following formula:

Address of A [ I ] = B + W * ( I – LB )

Where,B = Base addressW = Storage Size of one element stored in the array (in byte)I = Subscript of element whose address is to be foundLB = Lower limit / Lower Bound of subscript, if not specified assume 0 (zero)

Example:

Given the base address of an array B[1300…..1900] as 1020 and size of each element is 2 bytes in the memory. Find the address of B[1700].

Solution:

The given values are: B = 1020, LB = 1300, W = 2, I = 1700

Address of A [ I ] = B + W * ( I – LB )

Page 4: deepalipawar.files.wordpress.com€¦  · Web viewAddition operation traverses the matrices linearly, hence, has a time complexity of O(n), where n is the number of non-zero elements

= 1020 + 2 * (1700 – 1300)= 1020 + 2 * 400= 1020 + 800= 1820 [Ans]

2.a.Explain asymptotic notations-Big-O,Theta and omega with one example of each

) Θ Notation: The theta notation bounds a functions from above and below, so it defines exact asymptotic behavior.Let f(n) and g(n) be two functions then we can say that f(n) = O(g(n)) if and only if there exists positive constants c and n0, such that

f(n) ≤ cg(n) for all n≥n0

Ans: In the given Problem

Page 5: deepalipawar.files.wordpress.com€¦  · Web viewAddition operation traverses the matrices linearly, hence, has a time complexity of O(n), where n is the number of non-zero elements

Let f(n) and g(n) be two functions then we can say that f(n) =W(g(n)) if and only if there exists positive constants c and n0, such that

f(n) ≥ cg(n) for all n≥n0

Example

Page 6: deepalipawar.files.wordpress.com€¦  · Web viewAddition operation traverses the matrices linearly, hence, has a time complexity of O(n), where n is the number of non-zero elements

Let f(n) and g(n) be two functions then we can say that f(n) = Q(g(n)) if and only if there exists positive constants c1,c2and n0, such that

0≤ c1g(n) ≤ f(n) ≤ c2g(n) for all n≥n0

Page 7: deepalipawar.files.wordpress.com€¦  · Web viewAddition operation traverses the matrices linearly, hence, has a time complexity of O(n), where n is the number of non-zero elements

Example

Q2.b.Write Pseudo C/C++ code to perform polynomial multiplication using arrays.

struct poly{int nExpo;int nCoeff;};k=0; //multiplicationfor(i=0;i<nT1;i++){for(j=0;j<nT2;j++){P3[k].nCoeff=P1[i].nCoeff*P2[j].nCoeff; //multiplication of co-efficientsP3[k].nExpo=P1[i].nExpo+P2[j].nExpo; //addition of exponentsk++;}}

Page 8: deepalipawar.files.wordpress.com€¦  · Web viewAddition operation traverses the matrices linearly, hence, has a time complexity of O(n), where n is the number of non-zero elements

for(i=0;i<k;i++){for(j=0;j<k-1;j++){if(P3[j].nExpo<P3[j+1].nExpo){nTemp=P3[j].nCoeff;P3[j].nCoeff=P3[j+1].nCoeff;P3[j+1].nCoeff=nTemp;

nTemp=P3[j].nExpo;P3[j].nExpo=P3[j+1].nExpo;P3[j+1].nExpo=nTemp;}}}printf("\n Multiplication of two Polynomial Expression : ");for(i=0;i<k;i++)printf("(%dx^%d)+",P3[i].nCoeff,P3[i].nExpo);

Q.3.A.Write Pseudo code C/C++ code to represent doubly linked list as ADTstruct node{int data;struct node *next;struct node *prev;

}*head;

struct node *createnode(){struct node *newnode =(struct node*)malloc (sizeof(struct node));printf("enter data");scanf("%d",&newnode->data);newnode->next=NULL;newnode->prev=NULL;return(newnode);}

void accept(){int n;int i;struct node *temp;head=NULL;

Page 9: deepalipawar.files.wordpress.com€¦  · Web viewAddition operation traverses the matrices linearly, hence, has a time complexity of O(n), where n is the number of non-zero elements

printf("how many node u want to enter");scanf("%d",&n);

for(i=0;i<n;i++){struct node *newnode = createnode();if(head==NULL){head=newnode;

}else{temp=head;while(temp->next!=NULL){temp=temp->next;

}temp->next=newnode;newnode->prev=temp;//newnode->next=NULL;}}}

//-----------------------------------------------------------------------//

void display(){struct node *temp=head;while(temp!=NULL){printf("|%d\t|-<-->",temp->data);temp=temp->next;}printf("NULL");}

void insert_begning(){struct node *newnode=createnode();newnode->next=head;head->prev=newnode;head=newnode;display();}

Page 10: deepalipawar.files.wordpress.com€¦  · Web viewAddition operation traverses the matrices linearly, hence, has a time complexity of O(n), where n is the number of non-zero elements

//----------------------------------------------------------------//

void insert_end(){struct node *newnode=createnode();struct node *temp;temp=head;while(temp->next!=NULL){temp=temp->next;

}temp->next=newnode;newnode->prev=temp;newnode->next=NULL;display();}//--------------------------------------------------------------------------//

void insert_after(){struct node *newnode=createnode();struct node *temp,*temp1;int serno;printf(" after which node u want insert");scanf("%d",&serno);temp=head;while(temp->data!=serno){temp=temp->next;

}newnode->next=temp->next;temp->next->prev=newnode;temp->next=newnode;newnode->prev=temp;display();}//--------------------------------------------------------------//

void delete_begning(){struct node *temp;temp=head;head=head->next;temp->next=NULL;head->prev=NULL;free(temp);display();

Page 11: deepalipawar.files.wordpress.com€¦  · Web viewAddition operation traverses the matrices linearly, hence, has a time complexity of O(n), where n is the number of non-zero elements

}//--------------------------------------------------------------------------//

void delete_end(){struct node *temp;struct node *old;temp=head;while(temp->next!=NULL) //while start{old=temp;temp=temp->next;

} //while endold->next=NULL;temp->prev=NULL;free(temp);display();

}//-----------------------------------------------------------------//

void delete_after(){// struct node *newnode=createnode();

struct node *temp;struct node *temp1;struct node *temp2;int serno;printf(" after which node u want delete");scanf("%d",&serno);temp=head;while(temp->data!=serno){temp=temp->next;

}temp1=temp->next;temp2=temp1->next;temp->next=temp2;temp2->prev=temp->prev;temp1->next=NULL;free(temp1);display();}

Page 12: deepalipawar.files.wordpress.com€¦  · Web viewAddition operation traverses the matrices linearly, hence, has a time complexity of O(n), where n is the number of non-zero elements

Explain step by step conversion using stack for given infix exoression to prefix expression (( a / ( b + c- d )) * ( e- a ) * c)

Q.4.A.Write pseudo code C/C++ code to implement stack as an ADT

StartDeclaration of variablesclass stack{ int stk[5]; int top; public: stack() { top=-1; } void push(int x) { if(top > 4) { cout <<"stack over flow"; return; } stk[++top]=x; cout <<"inserted" <<x; } void pop() { if(top <0) begin cout <<"stack under flow"; return; } cout <<"deleted" <<stk[top--]; end void display() begin if(top<0) { cout <<" stack empty"; return; } for(int i=top;i>=0;i--) cout <<stk[i] <<" "; end};

Q.4.B.Write an algorithm to perform following operations on singly linked list 1.Reverse 2.Sort

1. Initialize three pointers prev as NULL, curr as head and next as NULL.

Page 13: deepalipawar.files.wordpress.com€¦  · Web viewAddition operation traverses the matrices linearly, hence, has a time complexity of O(n), where n is the number of non-zero elements

2. Iterate trough the linked list. In loop, do following.// Before changing next of current,// store next nodenext = curr->next

// Now change next of current// This is where actual reversing happenscurr->next = prev

// Move prev and curr one step forwardprev = currcurr = next

For sort()If Linked list is empty then make the node as head and return it.2) If value of the node to be inserted is smaller than value of head node, then insert the node at start and make it head.3) In a loop, find the appropriate node after which the input node (let 9) is to be inserted. To find the appropriate node start from head, keep moving until you reach a node GN (10 in the below diagram) who's value is greater than the input node. The node just before GN is the appropriate node (7).4) Insert the node (9) after the appropriate node (7) found in step 3.

Q.5.AWrite pseudo C/C++ code to represent deque and perform the following operations:1.Create queue2.Insert 3.Delete 4.Displayvoid initialize(dequeue *P){    P->rear=-1;    P->front=-1;} int empty(dequeue *P){    if(P->rear==-1)        return(1);        return(0);} int full(dequeue *P){    if((P->rear+1)%MAX==P->front)        return(1);        return(0);} 

Page 14: deepalipawar.files.wordpress.com€¦  · Web viewAddition operation traverses the matrices linearly, hence, has a time complexity of O(n), where n is the number of non-zero elements

void enqueueR(dequeue *P,int x){    if(empty(P))    {        P->rear=0;        P->front=0;        P->data[0]=x;    }    else    {        P->rear=(P->rear+1)%MAX;        P->data[P->rear]=x;    }} void enqueueF(dequeue *P,int x){    if(empty(P))    {        P->rear=0;        P->front=0;        P->data[0]=x;    }    else    {        P->front=(P->front-1+MAX)%MAX;        P->data[P->front]=x;    }} int dequeueF(dequeue *P){    int x;        x=P->data[P->front];        if(P->rear==P->front)    //delete the last element        initialize(P);    else        P->front=(P->front+1)%MAX;        return(x);} int dequeueR(dequeue *P){    int x;        x=P->data[P->rear];        if(P->rear==P->front)        initialize(P);    else        P->rear=(P->rear-1+MAX)%MAX;            return(x);

Page 15: deepalipawar.files.wordpress.com€¦  · Web viewAddition operation traverses the matrices linearly, hence, has a time complexity of O(n), where n is the number of non-zero elements

} void print(dequeue *P){    if(empty(P))    {        printf("\nQueue is empty!!");        exit(0);    }        int i;    i=P->front;        while(i!=P->rear)    {        printf("\n%d",P->data[i]);        i=(i+1)%MAX;    }        printf("\n%d\n",P->data[P->rear]);}

Q.5.B.What is circular queue?Explain advantages of circular queue over linear queue.

Circular Queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle.

Graphical representation of a circular queue is as follows...

Typically circular queues implement a linked-list design to manage the queue. This allows you to "insert" an artifact (e.g. object or data-structure) anywhere you like into a queue. This is very difficult within a linear queue (depending on the reference implementation). Additionally memory management becomes much easier to control and predominantly more efficient implementing a circular queue. In CircularQueue we utilize memory efficiently. because in queue when we delete any element only front increment by 1, but that position is not used later. so when we perform more add and delete operation, memory wastage increase. But in CQ

Page 16: deepalipawar.files.wordpress.com€¦  · Web viewAddition operation traverses the matrices linearly, hence, has a time complexity of O(n), where n is the number of non-zero elements

memory is utilized, if we delete any element that position is used later, because it is circular.

Explain shell sort and sort the given list using shell sort 08,03,02,11,05,14,00,02,09,04,20

Q8 a. The shell sort, sometimes called the “diminishing increment sort,” improves on the insertion sort by breaking the original list into a number of smaller sublists, each of which is sorted using an insertion sort. The unique way that these sublists are chosen is the key to the shell sort. Instead of breaking the list into sublists of contiguous items, the shell sort uses an increment i, sometimes called the gap, to create a sublist by choosing all items that are i items apart.

This can be seen in Figure 6. This list has nine items. If we use an increment of three, there are three sublists, each of which can be sorted by an insertion sort. After completing these sorts, we get the list shown in Figure 7. Although this list is not completely sorted, something very interesting has happened. By sorting the sublists, we have moved the items closer to where they actually belong.

Figure 8 shows a final insertion sort using an increment of one; in other words, a standard insertion sort. Note that by performing the earlier sublist sorts, we have now reduced the total number of shifting operations necessary to put the list in its final order. For this case, we need only four more shifts to complete the process.

Page 17: deepalipawar.files.wordpress.com€¦  · Web viewAddition operation traverses the matrices linearly, hence, has a time complexity of O(n), where n is the number of non-zero elements

We said earlier that the way in which the increments are chosen is the unique feature of the shell sort. The function shown in ActiveCode 1 uses a different set of increments. In this case, we begin with n2n2 sublists. On the next pass, n4n4 sublists are sorted. Eventually, a single list is sorted with the basic insertion sort. Figure 9 shows the first sublists for our example using this increment.The following invocation of the shellSort function shows the partially sorted lists after each increment, with the final sort being an insertion sort with an increment of one.

Write short note of stability of sorting.Compare heap sort with one example and discuss time complexity.

A sorting algorithm is said to be stable if two objects with equal keys appear in the same order in sorted output as they appear in the input array to be sorted.

Formally stability may be defined as,Let A be an array, and let < be a strict weak ordering on the elementsof A. A sorting algorithm is stable if-

i<j and A[i]= A[j] implies  π(i) < π(j)

where  πis the sorting permutation ( sorting moves A[i] to position  π(i) )Informally, stability means that equivalent elements retain their relative positions, after sorting.

Page 18: deepalipawar.files.wordpress.com€¦  · Web viewAddition operation traverses the matrices linearly, hence, has a time complexity of O(n), where n is the number of non-zero elements

Q7 b)Fibonacci Series Algorithm:

Start Declare variables i, a,b , show Initialize the variables, a=0, b=1, and show =0 Enter the number of terms of Fibonacci series to be printed Print First two terms of series Use loop for the following steps

-> show=a+b-> a=b-> b=show-> increase value of i each time by 1-> print the value of show

End

Example for shell sort

The Shell Sort

The shell sort, sometimes called the “diminishing increment sort,” improves on the insertion sort by breaking the original list into a number of smaller sublists, each of which is sorted using an insertion sort. The unique way that these sublists are chosen is the key to the shell sort. Instead of breaking the list into sublists of contiguous items, the shell sort uses an increment i, sometimes called the gap, to create a sublist by choosing all items that are i items apart.

This can be seen in Figure 6. This list has nine items. If we use an increment of three, there are three sublists, each of which can be sorted by an insertion sort. After completing these sorts, we get the list shown in Figure 7. Although this list is not completely sorted, something very interesting has happened. By sorting the sublists, we have moved the items closer to where they actually belong.

Page 19: deepalipawar.files.wordpress.com€¦  · Web viewAddition operation traverses the matrices linearly, hence, has a time complexity of O(n), where n is the number of non-zero elements

Figure 8 shows a final insertion sort using an increment of one; in other words, a standard insertion sort. Note that by performing the earlier sublist sorts, we have now reduced the total number of shifting operations necessary to put the list in its final order. For this case, we need only four more shifts to complete the process.

We said earlier that the way in which the increments are chosen is the unique feature of the shell sort. The function shown in ActiveCode 1 uses a different set of increments. In this case, we begin with n2

sublists. On the next pass, n4

sublists are sorted. Eventually, a single list is sorted with the basic insertion sort. Figure 9 shows the first sublists for our example using this increment.

Page 20: deepalipawar.files.wordpress.com€¦  · Web viewAddition operation traverses the matrices linearly, hence, has a time complexity of O(n), where n is the number of non-zero elements

The following invocation of the shellSort function shows the partially sorted lists after each increment, with the final sort being an insertion sort with an increment of one.