Sei sulla pagina 1di 22

ASSIGNMEN T SET# 1

MT0033 DATA STRUCTURES USING C SET- 1

Question#1 Define Data Structure? Explain the types of structured data type. Answer: Data structure is a particular way of storing and organizing data in a computer so that it can be used efficiently. Different kinds of data structures are suited to different kinds of applications, and some are highly specialized to specific tasks. For example, B-trees are particularly well-suited for implementation of databases, while compiler implementations usually use hash tables to look up identifiers. Data structures are used in almost every program or software system. Data structures provide a means to manage huge amounts of data efficiently, such as large databases and internet indexing services. Usually, efficient data structures are a key to designing efficient algorithms. Some formal design methods and programming languages emphasize data structures, rather than algorithms, as the key organizing factor in software design. Different types of Data structures are: Linear data structures: 1.Arrays: an array data structure or simply array is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key. An array is stored so that the position of each element can be computed from its index tuple by a mathematical formula. These arrays include: Sorted array: A sorted array is an array data structure in which each element is sorted in numerical, alphabetical, or some other order, and placed at equally spaced addresses in computer memory. It is typically used in computer science to implement static lookup tables to hold multiple values which has the same data type. Sorting an array is useful in organizing data in ordered form and recovering it rapidly. Parallel array: a parallel array is a data structure for representing arrays of records. It keeps a separate, homogeneous array for each field of the record, each having the same number of elements. Then, objects located at the same index in each array are implicitly the fields of a single record. Pointers from one object to another are replaced by array indices. Dynamic array: a dynamic array, growable array, resizable array, dynamic table, or array list is a random access, variable-size list data structure that allows elements to be added or removed. Varied length array: is an array data structure of automatic storage duration whose length is determined at run time (instead of at compile time).

Page 2

MT0033 DATA STRUCTURES USING C SET- 1

2. Lists Linked list: a linked list is a data structure consisting of a group of nodes which together represent a sequence. Under the simplest form, each node is composed of a datum and a reference (in other words, a link) to the next node in the sequence; more complex variants add additional links. This structure allows for efficient insertion or removal of elements from any position in the sequence.

Doubly linked list: a doubly linked list is a linked data structure that consists of a set of sequentially linked records called nodes. Each node contains two fields, called links that are references to the previous and to the next node in the sequence of nodes. The beginning and ending nodes' previous and next links, respectively, point to some kind of terminator, typically a sentinel node or null, to facilitate traversal of the list. If there is only one sentinel node, then the list is circularly linked via the sentinel node. It can be conceptualized as two singly linked lists formed from the same data items, but in opposite sequential orders.

Trees Binary Trees: a binary tree is a tree data structure in which each node has at the most two child nodes, usually distinguished as "left" and "right". Nodes with children are parent nodes, and child nodes may contain references to their parents. Outside the tree, there is often a reference to the "root" node (the ancestor of all nodes), if it exists. Any node in the data structure can be reached by starting at root node and repeatedly following references to either the left or right child.

Page 3

MT0033 DATA STRUCTURES USING C SET- 1

Binary Search Tree: a binary search tree (BST), which may sometimes also be called an ordered or sorted binary tree, is a node-based binary tree data structure which has the following properties: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees.

AVL Trees: an AVL tree is a self-balancing binary search tree, and it was the first such data structure to be invented.[1] In an AVL tree, the heights of the two child subtrees of any node differ by at most one. Lookup, insertion, and deletion all take O(log n) time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree rotations. T-Trees: a T-tree is a type of binary tree data structure that is used by main-memory databases, such as MySQL Cluster, Oracle TimesTen and MobileLite. A T-tree is a balanced index tree data structure optimized for cases where both the index and the actual data are fully kept in memory, just as a B-tree is an index structure optimized for storage on blocks oriented secondary storage devices like hard disks. Ttrees seek to gain the performance benefits of in-memory tree structures such as AVL trees while avoiding the large storage space overhead which is common to them. B-Trees: a B-tree is a tree data structure that keeps data sorted and allows searches, sequential access, insertions, and deletions in logarithmic time. The B-tree is a generalization of a binary search tree in that a node can have more than two children. The B-tree is optimized for systems that read and write large blocks of data. It is commonly used in databases and file systems.

Page 4

MT0033 DATA STRUCTURES USING C SET- 1

Heaps: is a specialized tree-based data structure that satisfies the heap property: if B is a child node of A, then key(A) key(B). This implies that an element with the greatest key is always in the root node, and so such a heap is sometimes called a max-heap. (Alternatively, if the comparison is reversed, the smallest element is always in the root node, which results in a min-heap.) The maximum number of children each node can have depends on the type of heap, but in many types it is at most two. The heap is one maximally-efficient implementation of an abstract data type called a priority queue. Heaps are crucial in several efficient graph algorithms such as Dijkstra's algorithm, and in the sorting algorithm heapsort.

Hashes Hash List: is typically a list of hashes of the data blocks in a file or set of files. Lists of hashes are used for many different purposes, such as fast table lookup (hash tables) and distributed databases (distributed hash tables). This article covers hash lists that are used to guarantee data integrity. A hash list is an extension of the old concept of hashing an item (for instance, a file). A hash list is usually sufficient for most needs, but a more advanced form of the concept is a hash tree.

A hash list with a top hash

Page 5

MT0033 DATA STRUCTURES USING C SET- 1

Hash Table: or hash map is a data structure that uses a hash function to map identifying values, known as keys (e.g., a person's name), to their associated values (e.g., their telephone number). Thus, a hash table implements an associative array. The hash function is used to transform the key into the index (the hash) of an array element (the slot or bucket) where the corresponding value is to be sought. Graphs: is an abstract data type that is meant to implement the graph and hypergraph concepts from mathematics. A graph data structure consists of a finite (and possibly mutable) set of ordered pairs, called edges or arcs, of certain entities called nodes or vertices. As in mathematics, an edge (x,y) is said to point or go from x to y. The nodes may be part of the graph structure, or may be external entities represented by integer indices or references. A graph data structure may also associate to each edge some edge value, such as a symbolic label or a numeric attribute (cost, capacity, length, etc.).

Question# 2 What do you mean by a queue? Write C program to implement an ordinary queue. Answer: A queue is a buffer abstract data structure providing services in computer science, transport and operations research where various entities such as data, objects, persons, or events are stored and held to be processed later. The most well-known operation of the queue is the First-In-First-Out (FIFO) queue process. In a FIFO queue, the first element in the queue will be the first one out; this is equivalent to the requirement that whenever an element is added, all elements that were added before have to be removed before the new element can be invoked. By convention, we name the queue insert operation enqueue and the remove operation dequeue. /******** C Program For Impelmetation Of Queue ***********/ #define MAXSIZE 10 struct st { int front,rear; int queue[MAXSIZE]; }; struct st s; int empty(void);

Page 6

MT0033 DATA STRUCTURES USING C SET- 1

int full(void); void add(void); void delete(void); void display(void); void main() { char ans; int ch; s.front = 0; s.rear = 0; do { clrscr(); printf("********Queue Program**********\n"); printf("1. ADD\n"); printf("2. DELETE\n"); printf("3. DISPLAY\n"); printf("4. QUIT\n"); printf("Enter Your Choice : "); scanf("%d",&ch); switch(ch) { case 1: add(); break; case 2: delete(); break; case 3: display(); break; case 4: exit(1); break; default: printf("INVALID CHOICE!!!!!!!!!!!!!!!!\n"); break; } printf("\nWant To Go To The Main Menu[y/n]"); flushall(); ans = getch();

Page 7

MT0033 DATA STRUCTURES USING C SET- 1

} while(ans == 'y' ans == 'Y'); printf("\nPress Any Key To Continue\n"); getch(); } int full(void) { if (s.rear == MAXSIZE) return(1); else return(0); } int empty(void) { if (s.front == s.rear + 1) return(1); else return(0); } void add(void) { char ch; int x; do { if(full() == 1) { printf("\n\nQueue Full\n"); break; } Else { s.rear = s.rear + 1; printf("\nEnter An Element to Be Added "); scanf("%d",&x); s.queue[s.rear] = x; if(s.rear == 1) s.front ++; } printf("\nDo You Want to Add More Elements[y/n]:"); flushall(); ch = getch(); } while(ch=='y' ch == 'Y');

Page 8

MT0033 DATA STRUCTURES USING C SET- 1

} void delete(void) { char ch; do { if(empty() == 1) { printf("\n\nQueue Empty\n"); break; } else { printf("% d Has Been Deleted!",s.queue[s.front]); s.front = s.front +1; } printf("\nWant to Delete More [y\n]"); flushall(); ch = getch(); } while(ch=='y' ch == 'Y'); } void display(void) { int i; clrscr(); if(empty () == 1) printf("\nQueue Empty!!"); else { printf("\nDisplaying Queue\n"); for(i = s.front;i printf("%d\n",s.queue[i]); } } /************ OUTPUT *************** **********Queue Program********** 1. ADD 2. DELETE 3. DISPLAY 4. QUIT Enter Your Choice : 1

Page 9

MT0033 DATA STRUCTURES USING C SET- 1

Enter An Element to Be Added 1 Do You Want to Add More Elements[y/n]:y Enter An Element to Be Added 2 Do You Want to Add More Elements[y/n]:y Enter An Element to Be Added 3 Do You Want to Add More Elements[y/n]:y Enter An Element to Be Added 4 Do You Want to Add More Elements[y/n]:y Enter An Element to Be Added 5 Do You Want to Add More Elements[y/n]:n Want To Go To The Main Menu[y\n] y **********Queue Program********** 1. ADD 2. DELETE 3. DISPLAY 4. QUIT Enter Your Choice : 3 Displaying Queue 1 2 3 4 5 Want To Go To The Main Menu[y\n] y **********Queue Program********** 1. ADD 2. DELETE 3. DISPLAY 4. QUIT Enter Your Choice : 2 1 Has Been Deleted!! Do You Want To Delete More?[y/n] n Want to Go To Main Menue[y/n] y **********Queue Program********** 1. ADD 2. DELETE 3. DISPLAY 4. QUIT Enter Your Choice : 3 Displaying Queue

Page 10

MT0033 DATA STRUCTURES USING C SET- 1

2 3 4 5 Want To Go To The Main Menu[y\n] y **********Queue Program********** 1. ADD 2. DELETE 3. DISPLAY 4. QUIT Enter Your Choice : 4 */ Question# 3 Show that Towers of Hanoi is O(2n). Answer: The puzzle can be solved by a recursive algorithm. To move a stack of N disks from one peg to another, simply follow the following steps: a. Move the top N-1 disks of the stack aside, on the spare peg. b. Move disk N in position on the other peg. c. Move the stack of N-1 disks on top of disk N. This method works because this reduces the puzzle of N disks to a puzzle of only N-1 disks. That in turn is reduced to a puzzle of N-2 disks, and so on until the puzzle is reduced to moving a stack containing only 1 disk, which is easy. This algorithm has exactly 2N-1 moves, because from the steps above it is easily seen that Length(N)=2Length(N-1)+1, and Length(1)=1, and the result then follows by induction. This solution is also minimal, in other words there is no shorter way to solve it, because every solution for N disks must reach the intermediate position with the top N-1 disks on the spare peg. The recursive algorithm works very well, but in practice there are several rules of thumb which can guide you: Every other move is a move of the smallest disk, i.e. the small disk is moved on move number 1, 3, 5, ... ,2N-1. The smallest disk visits each peg in turn, and is never moved back to the peg it came from on its previous move. In fact this is true of all disks (except for the largest), but it is more obvious with the smallest one since it is moved so often. On a move not involving the small disk (i.e. moves 2, 4, 6, ...) there is only one possible move choice. If the disks are numbered, then an even disk is never placed on top of an even disk, and an odd one never on top of another odd one. If there is an even number of disks then the first move takes the small disk to the second peg, with an odd number of disks the first move is to the third peg. This can be seen as an extension of the odd/even rule above; the bases of the pegs are also considered odd or

Page 11

MT0033 DATA STRUCTURES USING C SET- 1

even in such a way that the start and end positions follow the odd/even rule, and then the first move can be deduced. There are 3N possible positions, and 2N positions are encountered while solving the puzzle directly using the methods above. All the other 3N-2N positions break the odd/even rules by having two disks of the same parity on top of each other (or the largest disk on the middle peg). The odd/even rule always rules out one of the three available moves, so that you can only go forwards to the end or back to the beginning. If you stop in the middle of solving and forget what your last move was, then you may find yourself reversing previous moves and ending up back at the beginning. The rules of thumb also do not help you when you encounter one of the 3N-2N positions that do not lie on the direct route between the start and the end. In these cases the correct move can be deduced as follows: a. You want to move the stack of N disks to the third peg. You therefore want to put disk N on the third peg first. b. If the disk is in position, then the aim is to put all the smaller disks on top of it. If not, then the aim is to put all the smaller disks on the other peg. c. Repeat the above for this smaller stack of disks. This is best illustrated by example:

Here we want to move disk 4 from peg B to peg C. This means that we need all the smaller disks to be on peg A, so we must move disk 3 from peg C to peg A first. For this we need all disks smaller than 3 to be on peg B. Disk 2 is already on peg B, but disk 1 is not so this has to be moved to peg B. The correct move is therefore disk 1 from A to B. Similarly if we want to move back to start, to move disk 4 from B to A means that disk 3 and smaller must be on peg C. Disk 3 is already on C, so we must put disk 2 on C next. Disk 1 does not obstruct this, so the correct move is disk 2 from B to C. If we wanted all the disks on peg B instead, then the correct move would be move disk 1 from A to C. Note that this move does break the odd/even rule (disk 1 moves on top of disk 3), but that is only because the position itself already breaks that rule (disk 2 lies on disk 4). Show that Towers of Hanoi is O(2n) Let T(n) = the number of disk moves to move a tower of size n. To move a tower of size n from peg 1 to peg 3 you first move a tower of size n-1 from peg 1 to peg 2, then move a disk from peg 1 to peg 3, and finally move the tower of size n-1 from peg 2 to peg 3. The number of disk moves (T(n)) is the number of moves to move the tower of size n-1 (T(n-1)) twice plus the single disk move.

Page 12

MT0033 DATA STRUCTURES USING C SET- 1

T(n) = 2 T(n-1) + 1 where T(1) = 1 To prove that T(n) is O(2n), we must show that for a particular choice of c and N0, T(n) < c(2n-2) for all n N0 {since any function 2n - k is also O(2n)

--We need to strengthen the claim in order to prove the result -Choose c= 3 and N0 = 2. Base case: n = 2 T(2) = 2T(1) + 1 = 3 < c(2n-2) = 3 (22-2) = 6

True.

Inductive hypothesis: Assume P(n) is true --the statement for size n is true-Show that then P(n+1) is true. P(n): T(n) < 3(2n-2) P(n+1):T(n+1) < 3(2n+1-2) T(n+1) = 2T(n) + 1 < 2* 3(2n-2) + 1 = 3(2n+1-4) + 1 = 3(2n+1-2) -6 + 1 < 3(2n+1-2)

Question# 4 What do you mean by a Graph? How graphs are represented? Explain

Page 13

MT0033 DATA STRUCTURES USING C SET- 1

Answer: Graphs are visual representations. They are used to organize information to show patterns and relationships. A graph shows this information by representing it as a shape. Researchers and scientists often use tables and graphs to report findings from their research. In newspapers, magazine articles, and on television they are often used to support an argument or point of view. Graphs are represented in the following forms: Bar graphs Bar graphs should be used for categoric, ordered, and discrete variables. If the number of units in a discrete variable is large it may be displayed as a continuous variable.

Line graphs Line graphs should be used for continuous variables.

Pie graphs

Page 14

MT0033 DATA STRUCTURES USING C SET- 1

Pie graphs (sometimes called pie or circle charts) are used to show the parts that make up a whole. They can be useful for comparing the size of relative parts. Because it is difficult to compare different circle graphs, and often hard to compare the angles of different sectors of the pie, it is sometimes better to choose other sorts of graphs.

Histograms Use histograms when y-axis gives the frequency of, or occurrences for continuous data that has been sorted into groups, for example, 20-24 metres. All bars are usually of equal width. They can be turned into line graphs by connecting the middle of the top section of each vertical bar. Histograms are not joined up bar graphs and should not be used for categoric data (unless the number of units in each group is large).

Page 15

MT0033 DATA STRUCTURES USING C SET- 1

ASSIGNMEN T SET# 2

Page 16

MT0033 DATA STRUCTURES USING C SET- 1

Question#1 Define Tree? Explain Binary tree with its properties Answer: A tree data structure is a powerful tool for organizing data objects based on keys. It is equally useful for organizing multiple data objects in terms of hierarchical relationships (think of a ``family tree'', where the children are grouped under their parents in the tree). Trees are usually drawn pictorially like this (again, think of a ``family tree''), where data can be placed where the asterisks appear:
/ / \ * * \ * /|\ * ** * * /\ ... ...

The asterisks represent nodes; the node at the top is the root, the tree's ``starting point.'' The arcs between nodes are called branches. A node that has no branches underneath it is called a leaf. Real trees grow from their root upwards to the sky, but computer-science trees grow from the root downwards. When we examine a non-leaf node, we see that the node has trees growing underneath it, and we say that the node has children subtrees. For example, the root node, ``Animal'', has two children subtrees. Tree structures make an excellent alternative to arrays, especially when the data stored within them is keyed or has internal structure that allows one element to be related to, or ``saved within'' another. A binary tree is a tree data structure in which each node has at most two child nodes, usually distinguished as "left" and "right". Nodes with children are parent nodes, and child nodes may contain references to their parents. Outside the tree, there is often a reference to the "root" node (the ancestor of all nodes), if it exists. Any node in the data structure can be reached by starting at root node and repeatedly following references to either the left or right child. Properties of binary trees are: The number of nodes n in a perfect binary tree can be found using this formula: n = 2h + 1 1 where h is the depth of the tree. The number of nodes n in a complete binary tree is at least n = 2h and at most n = 2h + 1 1 where h is the depth of the tree. The number of leaf nodes L in a perfect binary tree can be found using this formula: L = 2h where h is the depth of the tree.

Page 17

MT0033 DATA STRUCTURES USING C SET- 1

The number of nodes n in a perfect binary tree can also be found using this formula: n = 2L 1 where L is the number of leaf nodes in the tree. The number of null links (absent children of nodes) in a complete binary tree of n nodes is (n+1). The number nL of internal nodes (non-leaf nodes) in a Complete Binary Tree of n nodes is n / 2.

For any non-empty binary tree with n0 leaf nodes and n2 nodes of degree 2, n0 = n2 + 1. Proof: Let n = the total number of nodes B = number of branches n0, n1, n2 represent the number of nodes with no children, a single child, and two children respectively. B = n - 1 (since all nodes except the root node come from a single branch) B = n1 + 2*n2 n = n1+ 2*n2 + 1 n = n0 + n1 + n2 n1+ 2*n2 + 1 = n0 + n1 + n2 ==> n0 = n2 + 1

Question#2 Write the algorithm and C program for sorting the numbers in ascending order using quick sort technique. Answer: Quicksort is a divide and conquer algorithm. Quicksort first divides a large list into two smaller sub-lists: the low elements and the high elements. Quicksort can then recursively sort the sub-lists. The steps of quicksort algorithm are: 1. Pick an element, called a pivot, from the list. 2. Reorder the list so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation. 3. Recursively sort the sub-list of lesser elements and the sub-list of greater elements. The base case of the recursion are lists of size zero or one, which never need to be sorted. #include <stdio.h> #define MAXELT 50 typedef int key; typedef int index;

Page 18

MT0033 DATA STRUCTURES USING C SET- 1

key list[MAXELT]; void main() { int i=-1,j,n; char t[10]; void quicksort(index,index); do { //read the list of numbers if (i!=-1) list[i++]=n; else i++; printf("\nEnter the numbers <End by #>"); fflush(stdin); scanf("%[^\n]",t); if (sscanf(t,"%d",&n)<1) break; } while (1); //sort //print

quicksort(0,i-1); printf("The list obtained is "); for (j=0;j<i;j++) printf("\n %d",list[j]); }

void quicksort(index first,index last) { void split(index,index,index*); index splitpoint; if (first<last) { split(first,last,&splitpoint); //split quicksort(first,splitpoint-1); //sort the first sub-list quicksort(splitpoint+1,last); //sort the second sub-list } } void split(index first,index last,index *splitpoint) { key x; index unknown;

Page 19

MT0033 DATA STRUCTURES USING C SET- 1

void interchange(int*,int*); x=list[first]; *splitpoint=first; //find the split-point element //find the splitpoint

for (unknown=first+1;unknown<=last;unknown++) { //move through the list if (list[unknown]<x) { //comparing each element //with the split-point element *splitpoint=(*splitpoint)+1; //move the splitpoint interchange(&list[*splitpoint],&list[unknown]); //move the split-point element } } interchange(&list[first],&list[*splitpoint]); //get the split-point element //in the middle return; } void interchange(int *x,int *y) { int temp; temp=*x; *x=*y; *y=temp; } //solution 1 ends Question#3 What is the significance of a Depth First Search (DFS)? How it is implemented? Answer: is an algorithm for traversing or searching a tree, tree structure, or graph. One starts at the root (selecting some node as the root in the graph case) and explores as far as possible along each branch before backtracking. DFS is an uninformed search that progresses by expanding the first child node of the search tree that appears and thus going deeper and deeper until a goal node is found, or until it hits a node that has no children. Then the search backtracks, returning to the most recent node it hasn't finished exploring. In a non-recursive implementation, all freshly expanded nodes are added to a stack for exploration. //interchange

Page 20

MT0033 DATA STRUCTURES USING C SET- 1

Question#4 Explain the following (a) Sequential files (b) Index-sequential files Anwser: (a) Sequential files A sequential file contains records organized by the order in which they were entered. The order of the records is fixed. Records in sequential files can be read or written only sequentially. After you have placed a record into a sequential file, you cannot shorten, lengthen, or delete the record. However, you can update (REWRITE) a record if the length does not change. New records are added at the end of the file. If the order in which you keep records in a file is not important, sequential organization is a good choice whether there are many records or only a few. Sequential output is also useful for printing reports. Quite possibly, the best reason for using sequential files is their degree of portability to other programs, programming languages, and computers. Because of this, you can often look at sequential files as the common denominator of data processing, since they can be read by word-processing programs and editors (such as PowerBASIC's), absorbed by other applications (such as database managers), and sent over the Internet to other computers. The idea behind sequential files is simplicity itself: write to them as though they were the screen and read from them as though they were the keyboard. Create a sequential file using the following steps: 1. Open the file in sequential output mode. To create a file in PowerBASIC, you must use the OPEN statement. Sequential files have two options to prepare a file for output: 2. OUTPUT: If a file does not exist, a new file is created. If a file already exists, its contents are erased, and the file is then treated as a new file. 3. APPEND: If a file does not exist, a new file is created. If a file already exists, PowerBASIC appends (adds) data at the end of that file. 4. Output data to a file. Use WRITE# or PRINT# to write data to a sequential file. 5. Close the file. The CLOSE statement closes a file after the program has completed all I/O operations. 6. To read a sequential file: 7. First, OPEN the file in sequential INPUT mode. This prepares the file for reading.

Page 21

MT0033 DATA STRUCTURES USING C SET- 1

Read data in from the file. Use PowerBASIC's INPUT# or LINE INPUT# statements. 9. Close the file. The CLOSE statement closes a file after the program has completed all I/O operations.
8.

(b) Index-sequential files

Records in indexed sequential files are stored in the order that they are written to the disk. Records may be retrieved in sequential order or in random order using a numeric index to represent the record number in the file. When an indexed sequential file is opened, the record pointer is positioned at the first record. Subsequent I/O operations change the location of the pointer. Note: Some I/O operations do not move the pointer. For example, to read all the records from an indexed sequential file in order, you would open the file and read the records without specifying an index. This would move through the file in sequential order and end when the last record was read. To read a specific record from an indexed sequential file, you would include the KEY= parameter in the READ (or associated input) statement. The "key" in this case would be a specific record number (e.g., the number 35 would represent the 35th record in the file). The direct access to a record moves the record pointer, so that subsequent sequential access would take place from the new record pointer location, rather than the beginning of the file. Indexed sequential files are commonly used for transaction files because they take less disk space than keyed files, and are faster to read from beginning to end than a keyed file.

Page 22

Potrebbero piacerti anche