Download data structure - Karnataka State Open University

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

The Measure of a Man (Star Trek: The Next Generation) wikipedia , lookup

Data (Star Trek) wikipedia , lookup

Pattern recognition wikipedia , lookup

Time series wikipedia , lookup

Transcript
KARNATAKA STATE OPEN UNIVERSITY
I SEMESTER MCA EXAMINATION
DATA STRUCTURE
Time: 3 Hours
Max. Marks: 75
SECTION A
ANSWER THE QUESTIONS:
1. Define Data structure?
2. What is the difference between Recursion and iteration?
3. List any two applications of stacks
4. State any two application of queue
5. What do you mean by header nodes?
SECTION B
ANSWER ANY TWO QUESTIONS:
6. What is binary tree.
7. Explain circular linked list with example.
8. Discuss stack & its operation in detail.
SECTION C
ANSWER ANY TWO QUESTIONS:
9. What do you mean by dynamic memory allocation?
10. Explain Heap Creation And Insertion With Example.
11. Explain Depth-first algorithm.
12. What are the different notations used for time complexity in sorting
techniques?
Ans. The run-time complexity for the worst-case scenario of a given algorithm can
sometimes be evaluated by examining the structure of the algorithm and making some
simplifying assumptions. Consider the following pseudocode:
1
2
3
4
5
6
7
get a positive integer from input
if n > 10
print "This might take a while..."
for i = 1 to n
for j = 1 to i
print i * j
print "Done!"
A given computer will take a discrete amount of time to execute each of the instructions
involved with carrying out this algorithm. The specific amount of time to carry out a given
instruction will vary depending on which instruction is being executed and which computer is
executing it, but on a conventional computer, this amount will be deterministic.[9] Say that the
actions carried out in step 1 are considered to consume time T1, step 2 uses time T2, and so
forth.
In the algorithm above, steps 1, 2 and 7 will only be run once. For a worst-case evaluation, it
should be assumed that step 3 will be run as well. Thus the total amount of time to run steps
1-3 and step 7 is:
The loops in steps 4, 5 and 6 are trickier to evaluate. The outer loop test in step 4 will execute
( n + 1 ) times (note that an extra step is required to terminate the for loop, hence n + 1 and
not n executions), which will consume T4( n + 1 ) time. The inner loop, on the other hand, is
governed by the value of i, which iterates from 1 to n. On the first pass through the outer
loop, j iterates from 1 to 1: The inner loop makes one pass, so running the inner loop body
(step 6) consumes T6 time, and the inner loop test (step 5) consumes 2T5 time. During the
next pass through the outer loop, j iterates from 1 to 2: the inner loop makes two passes, so
running the inner loop body (step 6) consumes 2T6 time, and the inner loop test (step 5)
consumes 3T5 time.
13. How do you push and pop elements in a linked List?
Ans.
14. What do you mean by height of the tree?
15. What is Bottom -up design strategy?
Ans. Top-down and bottom-up are both strategies of information processing and
knowledge ordering, used in a variety of fields including software, humanistic and
scientific theories (see systemics), and management and organization. In practice, they
can be seen as a style of thinking and teaching. A bottom-up approach (also known as
inductive reasoning,[1] and in many cases used as a synonym of synthesis) is the piecing
together of systems to give rise to grander systems, thus making the original systems subsystems of the emergent system. Bottom-up processing is a type of information
processing based on incoming data from the environment to form a perception.
Information enters the eyes in one direction (input), and is then turned into an image by
the brain that can be interpreted and recognized as a perception (output). In a bottom-up
approach the individual base elements of the system are first specified in great detail.
These elements are then linked together to form larger subsystems, which then in turn
are linked, sometimes in many levels, until a complete top-level system is formed. This
strategy often resembles a "seed" model, whereby the beginnings are small but
eventually grow in complexity and completeness.
16. Differentiate between arrays and lists.
Ans. The difference between arrays and linked lists are:
- Arrays are linear data structures. Linked lists are linear and non-linear data structures.
- Linked lists are linear for accessing, and non-linear for storing in memory
- Array has homogenous values. And each element is independent of each other positions.
Each node in the linked list is connected with its previous node which is a pointer to the
node.
- Array elements can be modified easily by identifying the index value. It is a complex
process for modifying the node in a linked list.
- Array elements can not be added, deleted once it is declared. The nodes in the linked list can
be added and deleted from the list.
17. What do you mean by linear searching?
Ans. Linear search is the simplest search algorithm; it is a special case of brute-force search.
Its worst case cost is proportional to the number of elements in the list; and so is its expected
cost, if all list elements are equally likely to be searched for. Therefore, if the list has more
than a few elements, other methods (such as binary search or hashing) will be faster, but they
also impose additional requirements. linear search is the most basic of search algorithm you
can have. A linear search sequentially moves through your collection (or data structure)
looking for a matching value.
Implementation
function findIndex(values, target) {
for(var i = 0; i < values.length; ++i){
if (values[i] == target) { return i; }
}
return -1;
}
findIndex([7, 3, 6, 1, 0], 6)
18. What do you mean by sorting?
Ans. Sorting is one of the most important operations performed by computers. In the
days of magnetic tape storage before modern data-bases, it was almost certainly the
most common operation performed by computers as most "database" updating was
done by sorting transactions and merging them with a master file. It's still important for
presentation of data extracted from databases: most people prefer to get reports sorted
into some relevant order before wading through pages of data!
PART – B
(5x10=50)
Answer any five:
1. With an example explain for transforming infix expression into postfix
expression.
2. Explain how do you calculate the running time of a program?
Ans. clock_t startClock,finishClock;
double timeCount;
startClock = clock();
//-----your sort function goes here here-------finishClock = clock();
timeCount = finishClock - startClock ;
timeCount will give you ELAPSED CLOCK. If you divide that by 100 ie:
timeCount/100...you will get ELAPSED TIME.
Also, dont forget to import the following.
#include <time.h>
#include <ctime>
3. What is Abstract Data type in data structure? Explain in detail
Ans. Abstract data type (ADT) is a mathematical model for a certain class of data structures
that have similar behavior; or for certain data types of one or more programming languages
that have similar semantics. An abstract data type is defined indirectly, only by the operations
that may be performed on it and by mathematical constraints on the effects (and possibly
cost) of those operations.[1]
For example, an abstract stack could be defined by three operations: push, that inserts some
data item onto the structure, pop, that extracts an item from it (with the constraint that each
pop always returns the most recently pushed item that has not been popped yet), and peek,
that allows data on top of the structure to be examined without removal. When analyzing the
efficiency of algorithms that use stacks, one may also specify that all operations take the
same time no matter how many items have been pushed into the stack, and that the stack uses
a constant amount of storage for each element.
Abstract data types are purely theoretical entities, used (among other things) to simplify the
description of abstract algorithms, to classify and evaluate data structures, and to formally
describe the type systems of programming languages. However, an ADT may be
implemented by specific data types or data structures, in many ways and in many
programming languages; or described in a formal specification language. ADTs are often
implemented as modules: the module's interface declares procedures that correspond to the
ADT operations, sometimes with comments that describe the constraints. This information
hiding strategy allows the implementation of the module to be changed without disturbing the
client programs.
The term abstract data type can also be regarded as a generalised approach of a number of
algebraic structures, such as lattices, groups, and rings.[2] This can be treated as part of
subject area of artificial intelligence. The notion of abstract data types is related to the
concept of data abstraction, important in object-oriented programming and design by contract
methodologies for software development
An abstract data type is defined as a mathematical model of the data objects that make up a
data type as well as the functions that operate on these objects. There are no standard
conventions for defining them. A broad division may be drawn between "imperative" and
"functional" definition styles.
Instance creation
Some algorithms need to create new instances of some ADT (such as new variables, or new
stacks). To describe such algorithms, one usually includes in the ADT definition a create()
operation that yields an instance of the ADT, usually with axioms equivalent to

the result of create() is distinct from any instance S in use by the algorithm.
This axiom may be strengthened to exclude also partial aliasing with other instances. On the
other hand, this axiom still allows implementations of create() to yield a previously created
instance that has become inaccessible to the program.
Preconditions, postconditions, and invariants
In imperative-style definitions, the axioms are often expressed by preconditions, that specify
when an operation may be executed; postconditions, that relate the states of the ADT before
and after the execution of each operation; and invariants, that specify properties of the ADT
that are not changed by the operations.
4. Explain the advantages of ADT operations?
Ans.
The implementor of the class can change the implementation for maintenance, bug
fixes or optimization reasons, without disturbing the client code.

The data type is defined as a set of high-level services with a semantic contract
defining both the output that is provided and the input that is required from the client.
This actually correspond to the general definition of a type in programming: a type is
defined as a set of possible values and a set of operations available on these values.

Encapsulation
Abstraction provides a promise that any implementation of the ADT has certain properties
and abilities; knowing these is all that is required to make use of an ADT object. The user
does not need any technical knowledge of how the implementation works to use the ADT. In
this way, the implementation may be complex but will be encapsulated in a simple interface
when it is actually used.

Localization of change
Code that uses an ADT object will not need to be edited if the implementation of the ADT is
changed. Since any changes to the implementation must still comply with the interface, and
since code using an ADT may only refer to properties and abilities specified in the interface,
changes may be made to the implementation without requiring any changes in code where the
ADT is used.

Flexibility
Different implementations of an ADT, having all the same properties and abilities, are
equivalent and may be used somewhat interchangeably in code that uses the ADT. This gives
a great deal of flexibility when using ADT objects in different situations. For example,
different implementations of an ADT may be more efficient in different situations; it is
possible to use each in the situation where they are preferable, thus increasing overall
efficiency.
5. Write a program in C++ to search an elements in an array using binary search.
Ans. #include<iostream.h>
#include<conio.h>
int bsearch(int AR[], int N, int VAL);
int main()
{
int AR[100],n,val,found;
cout<<"Enter number of elements you want to insert ";
cin>>n;
cout<<"Enter element in ascending order\n";
for(int i=0;i<n;i++)
{
cout<<"Enter element "<<i+1<<":";
cin>>AR[i];
}
cout<<"\nEnter the number you want to search ";
cin>>val;
found=bsearch(AR,n,val);
if(found==1)
cout<<"\nItem found";
else
cout<<"\nItem not found";
getch();
return 0;
}
int bsearch(int AR[], int N, int VAL)
{
int Mid,Lbound=0,Ubound=N-1;
while(Lbound<=Ubound)
{
Mid=(Lbound+Ubound)/2;
if(VAL>AR[Mid])
Lbound=Mid+1;
else if(VAL<AR[Mid])
Ubound=Mid-1;
else
return 1;
}
return 0;
}
6. Analyse the performance of selection sort algorithm ?
7. Explain Heap Sort with an example
Ans. Heapsort is a two step algorithm.
The first step is to build a heap out of the data.
The second step begins with removing the largest element from the heap. We insert the
removed element into the sorted array. For the first element, this would be position 0 of the
array. Next we reconstruct the heap and remove the next largest item, and insert it into the
array. After we have removed all the objects from the heap, we have a sorted array. We can
vary the direction of the sorted elements by choosing a min-heap or max-heap in step one.
Heapsort can be performed in place. The array can be split into two parts, the sorted array and
the heap. The storage of heaps as arrays is diagrammed at Binary heap#Heap
implementation.The heap's invariant is preserved after each extraction, so the only cost is that
of extraction.
Heapsort primarily competes with quicksort, another very efficient general purpose nearly-inplace comparison-based sort algorithm.
Quicksort is typically somewhat faster due to better cache behavior and other factors, but the
worst-case running time for quicksort is O(n2), which is unacceptable for large data sets and
can be deliberately triggered given enough knowledge of the implementation, creating a
security risk. See quicksort for a detailed discussion of this problem and possible solutions.
Thus, because of the O(n log n) upper bound on heapsort's running time and constant upper
bound on its auxiliary storage, embedded systems with real-time constraints or systems
concerned with security often use heapsort.
Heapsort also competes with merge sort, which has the same time bounds. Merge sort
requires Ω(n) auxiliary space, but heapsort requires only a constant amount. Heapsort
typically runs faster in practice on machines with small or slow data caches. On the other
hand, merge sort has several advantages over heapsort:

Like quicksort, merge sort on arrays has considerably better data cache performance,
often outperforming heapsort on modern desktop computers because merge sort




frequently accesses contiguous memory locations (good locality of reference);
heapsort references are spread throughout the heap.
Heapsort is not a stable sort; merge sort is stable.
Merge sort parallelizes well and can achieve close to linear speedup with a trivial
implementation; heapsort is not an obvious candidate for a parallel algorithm.
Merge sort can be adapted to operate on linked lists with O(1) extra space.[7] Heapsort
can be adapted to operate on doubly linked lists with only O(1) extra space
overhead.[citation needed]
Merge sort is used in external sorting; heapsort is not. Locality of reference is the
issue.
Introsort is an interesting alternative to heapsort that combines quicksort and heapsort to
retain advantages of both: worst case speed of heapsort and average speed of quicksort.
8. Write an algorithm and program to implement a doubly linked list.