DATA STRUCTIURES SFDSGFBFCVBFCBGJFBCV, Exams of Data Structures and Algorithms

DATA STRUCTURESFGFHFGHGJHGNHGNFG

Typology: Exams

2017/2018

Uploaded on 04/29/2018

shwetha-kulloli
shwetha-kulloli 🇮🇳

5

(1)

2 documents

1 / 49

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
DATA STRUCTURES
ABSTRACT DATA TYPES;
In programming, a situation occurs when a built in data types are not enough to handle
the complex data structures.
In such cases, a programmer needs to define everything related to the data type such as
how the data values are stored, the possible operations that can be carried out with the
custom data types are called Abstract data type.
e.g. In ‘C’ structures .
For example , if the programmer wants to define ‘date ‘ data type , which is not available
in ‘C’, he/she can create it using struct.
TYPES OF DATA STRUCTURES:
A data structure is a structured set of variables associated with one another in different
ways, co-operatively defining components in the system & capable of being operated
upon in the program.
The following operations are done on data structures:
1. Data organization or clubbing
2. Accessing technique
3. Manipulating selections for information
Data structures have been classified in several ways.
Linear :
In linear data structures , values are arranged in linear fashion. Arrays , linked
lists, stacks & queues are examples of linear data structures, in which values are stored in
a sequence.
Non-linear :
This type is opposite to linear. The data values in this structure are not arranged in
order. Tree, graph, table & sets are examples of non-linear data structures.
Homogenous:
In this type of data structures, values of the same types of data are stored as in an
array.
Non-homogenous:
In this type of data structures, data values of different types are grouped , as in
structures & classes.
ata Structures
Shwetha Kulloli, PeopleTree BCA,Belgaum Page 1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31

Partial preview of the text

Download DATA STRUCTIURES SFDSGFBFCVBFCBGJFBCV and more Exams Data Structures and Algorithms in PDF only on Docsity!

DATA STRUCTURES

ABSTRACT DATA TYPES;

In programming, a situation occurs when a built in data types are not enough to handle the complex data structures.

In such cases, a programmer needs to define everything related to the data type such as

how the data values are stored, the possible operations that can be carried out with the custom data types are called Abstract data type. e.g. In ‘C’ structures. For example , if the programmer wants to define ‘date ‘ data type , which is not available in ‘C’, he/she can create it using struct.

TYPES OF DATA STRUCTURES:

A data structure is a structured set of variables associated with one another in different ways, co-operatively defining components in the system & capable of being operated upon in the program.

The following operations are done on data structures:

  1. Data organization or clubbing
  2. Accessing technique
  3. Manipulating selections for information

Data structures have been classified in several ways.

Linear : In linear data structures , values are arranged in linear fashion. Arrays , linked lists, stacks & queues are examples of linear data structures, in which values are stored in a sequence.

Non-linear :

This type is opposite to linear. The data values in this structure are not arranged in order. Tree, graph, table & sets are examples of non-linear data structures.

Homogenous:

In this type of data structures, values of the same types of data are stored as in an array.

Non-homogenous:

In this type of data structures, data values of different types are grouped , as in structures & classes.

dynamic:

In dynamic data structures such as references & pointers , size & memory locations can be changed during program execution.

Static:

Static keyword in C is used to initialize the variable to 0(NULL). The value of a

static variable remains in the memory throughout the program. Value of static variable persists.

PRIMITIVE & NON-PRIMITIVE DATA STRUCTURES & OPERATION

Primitive Data structures:

The integers, float, character data, pointer & reference are primitive data structures. The built-in data types are called as primitive data type.

NOTE:

Primitive data structures are normally , directly operated upon by machine-level instructions.

Non_Primitive Data structures:

These are more complex data structures. These data structures are derived from the Primitive data structures. They stress on formation of sets of homogeneous & heterogeneous data elements. The different operations that are performed on data are nothing but designing of data structures. The following operations can be performed on data structures.

  1. CREATE
  2. DESTROY
  3. SELECT
  4. UPDATE

1.An operation typically used in combination with data & that creates a data structure is known as creation. This operation reserves memory for the program elements. It can be carried out at

compile time & run time. e.g. int x;

Here, variable x is declared & memory is allotted to it.

2.The destroy operation destroys the data structure. This is not an essential operation. When the program execution ends, the data structure is automatically destroyed & the memory allocated is eventually de-allocated.

This tells the compiler three things about the variable pt_name.

  1. The asterisk(*) tells that the variable pt_name is a pointer variable.
  2. (^) pt_name needs a memory location.
  3. pt_name points to a variable of type data type.

e.g.

*int p; declares a variable p as a pointer variable , that points to an integer data type.

*float x; declares a variable x as a pointer variable, that points to floating point variable.

Once a pointer variable has been declared, it can be made to point to a variable using an assignment statement such as p=&number; which causes p point to number.

That is, p now contains the address of number.

This is known as pointer ‘initialization’.

Remember:

  1. (^) We must ensure that the pointer variables always point to the corresponding type of data.
  2. Assigning the absolute address to a pointer variable is prohibited. (e.g. int *p; p=5368;).
  3. A pointer variable can be initialized in its declaration itself. e.g. int x,*p=&x;

note: The statement int *p=&x,x; is invalid. As the target variable x is not declared first.

Accessing a variable through its pointer: Once a pointer has been assigned the address of the variable, we can access the value of the variable using another unary operator (asterisk), known as ‘indirection operator’. e.g. int number,p,n; number = 179; p=&number; n=p; / it will store the value 179 to n / / it is equivalent to n=number */

Machine representation of Pointers:

Internally, a pointer is stored in 2 bytes, regardless of the variable type to which it points.

Example 2: (refer tc\cdatap\sizep) Example 3:( refer tc\cdatap\sizeptr)

Dynamic Memory Allocation:

When a C function is executed, the compiler during compilation reads the source files, and from the various declarations determines the memory requirement & arranges to allocate that amount of memory. Whenever we declare arrays , it is necessary to dimension arrays to some maximum size. since it is not always possible to predict what the array size will be , this technique can waste memory if the amount of data is much less than the maximum.

Also there is no way to increase or decrease the size of an array at the run time.

This problem of allocating right amount of memory for the arrays, when the precise size of input is not known, can be solved using the concept of Dynamic Memory Allocation

Note: Dynamic Memory Allocation is allocating the memory at the run time(while execution) instead of allocating at the compilation time.

The following functions are the part of ‘C’s standard library.

malloc(): Each time a memory request is made by using malloc(), a portion of the remaining free

memory is allocated.

Function declaration :

(cast-type *)malloc(unsigned int size); or void *malloc(unsigned int size);

This function allocates memory dynamically from the free memory or the memory not being used by the program.

Argument list unsigned int size size is the number of bytes to be allotted

Return value void* This is newly allocated

realloc()

Using this function we can alter the size of previously allocated memory. We can increase or reduce the size of the memory.

Function Declaration (cast-type *)realloc(ptr,size) or (void *) realloc(ptr,size);

This function changes the size of an allocated block of memory that was allocated using malloc or calloc function.

e.g. ptr = malloc(size);

then reallocation of space may be done by the statement ptr = realloc(ptr,newsize);

Example 5 :(refer rmemory)

Memory allocation Process: Note: The program instructions, Global & static variables are stored in a region known as

permanent storage area. Local variables are stored in another area called stack. The memory space that is located between these two regions is available for dynamic allocation, during execution of the program. This free memory region is called heap. The size of heap keeps changing when program is executed due to creation & death of variables, that are local to functions & blocks.

File Management in ‘C’:

Introduction: we know the functions such as scanf & printf to read & write data. These are console oriented I/O functions which always use the terminal(keyboard & screen) as the target place. this can be used as long as data is small. However, many real-life problems involve large volume of data & in such situations, the console oriented I/O operations pose two major problems.

  1. It becomes cumbersome & time consuming to handle large volumes of data through terminals.
  2. The entire data is lost when either the program is terminated or the computer is turned off.

It is therefore necessary to have a more flexible approach where data can be stored on the disks & read whenever necessary, without destroying the data. This method employs the concept of file to store data.

File:

A file is a place on the disk where a group of related data is stored. The basic file operations are:

  • naming a file.
  • (^) opening a file.
  • reading data from a file.
  • writing data to a file.
  • closing a file.

There are two distinct ways to perform file operations in ‘C’. The first one is known as the low level I/O & uses UNIX system calls. The second method is referred to as high level I/O operation & uses functions in ‘C’s standard I/O library.

Defining & Opening a File: If we want to store data in a file in the secondary memory, we must specify certain things about the file, to the operating system. They include

  1. Filename.
  2. Data structure
  3. Purpose

Filename is a string of characters. It may contain two parts, primary name & an optional period(dot) with the extension. e.g text.c student.dat etc. Data structure of a file is defined as FILE in the library of standard I/O function definitions. therefore, all files should be declared as type FILE before they are used. Note: FILE is a defined data type. When we open a file we can do read or write operation with it. We must specify whether we want to write data or read the already existing data.

The general format for opening a file: FILE *fp; fp=fopen(“filename”,”mode”);

The first statement declares the variable fp as a “pointer to the data type FILE.”

The second statement opens the file named filename & assigns an identifier to the FILE type pointer fp.

This pointer contains all the information about the file & is used as a communication link between the system & the program.

e.g

…. …. FILE p1,p2; p1=fopen(“INPUT”,”w”); p2=fopen(“OUPUT”,”r”); .… …. fclose(p1); fclose(p2); …. This program opens two files and closes them after all operations on them are completed.

Once a file is closed, its pointer can be re-used for another file.

Input/Output Operations On Files: Once a file is opened , reading out of it or writing to it is accomplished using the standard I/O routines that are listed below: fopen() creates a new file for use opens an existing file for use fclose() Closes a file which has been opened for use getc() Reads a character from a file putc() Writes a character to a file fprintf() Writes a set of data values to a file fscanf() Reads a set of data values from a file getw() Reads an integer from a file putw() Writes an integer to a file fseek() Sets the position to a desired point in the file. ftell() Gives the current position in the file (in terms of bytes from the start) rewind() sets the position to the beginning of the file.

The getc() and putc() functions: The simplest file I/O functions are getc() and putc(). These are analogous to getchar () and putchar() functions & handle one character at a time.

Assume that a file is opened with mode w and file pointer fp1. Then the statement putc(c,fp1); writes the character contained in the character variable c , to the file associated with FILE pointer fp1.

Similarly, getc() is used to read a character from a file that has been opened in read mode. e.g. c=getc(fp2); would read a character from the file whose file pointer is fp2.

Note: The file pointer moves by one character position for every operation of getc() or putc().

The getc() will return end-of-file marker EOF , when the end of the file has been reached.

Therefore, reading should be terminated when EOF is encountered.

Example 6: (refer rwfile)

Note : (ctrl)and z together ,is used to indicate the end of the data.

The getw() & putw() functions: The getw() & putw() are integer-oriented functions. They are similar to getc() & putc() functions and are used to read and write integer values.

The general format is, putw(integer,fp); getw(fp); Example 7:(refer intfile)

Note: Note that when we type -1, the reading is terminated & the file is closed.

The fprintf() & fscanf() functions: So far , we have seen functions which can handle only one character or integer at a time. Most compilers support two other functions , namely fscanf() & fprintf().

The functions fprintf() & fscanf() perform I/O operations that are identical to printf() & scanf (), except that they work on files.

The general format is, fprintf (fp,”control string”,list); fp – is a file pointer associated with a file that has been opened for writing. control string- contains output specifications for the item in the list. list – may include variables, constants and strings.

e.g. fprintf(f1,”%s %d %f”,name,age,7.5); Here , name is an array variable of type char and age is an int variable.

This condition is used to test whether a file has been opened or not.

Random access to File: When we are interested in accessing only a particular part of a file & not in reading the other parts we can use the functions fseek(), ftell() & rewind() available in I/O library.

ftell(): This function takes a file pointer and returns a number of type long , that corresponds to the current position. This function is useful in saving the current position of a file, which can be used later in the program. e.g. n=ftell(fp); n would give the relative offset (in bytes) of the current position. This means that n bytes have already been read(or written).

rewind(): This function takes a file pointer & resets the position to the start of the file. e.g. rewind(fp); n=ftell(fp);

Would assign 0 to n because the file position has been set to the start of the file by rewind().

Note: The first byte in the file is numbered as 0, second as 1, and so on. This function helps us in reading a file more than once, without having to close & open the file.

fseek(): This function is used to move the file position to a desired location within the file. The general format is, fseek( file ptr,offset,position)

file ptr is a pointer to the file concerned, offset is a number or variable of type long. The offset specifies the number of positions(bytes) to be moved from the location specified by position. The position can take one of the following three values.

Value Meaning

0 Beginning of the file 1 Current Position (^2) End of file

Note: The offset may be positive – meaning move forwards.

or negative – meaning move backwards.

e.g. fseek(fp,m,1) go forward by m bytes fseek(fp,m,0) move to (m+1)th byte in the file. fseek(fp,-m,1) go backward by m bytes from the current position fseek(fp,-m,2) go backward by m bytes from the end

Example 9: (refer fseete)

Example 10 :(errf)

Recursion

Introduction to Function: A function is a block of statements , that can be used to perform a specific task. A function has the following parts

  • Function prototype declarations
  • (^) definition of a function
  • Actual & formal arguments
  • Return statement
  • Invoking Function

Function Prototype: The prototypes of built-in functions are given in the respective header files. We include them using ‘# include ‘ directive.

A prototype statement helps the compiler to check the return and argument types of the function.

A function prototype declaration consists of function’s return type,name & argument list.

There are various situations when we need to execute a block of statements for a

number of times depending on condition, at that time recursion is very useful.

Note: Recursion is used to solve a problem, which has iterations in reverse order.

When a function calls itself recursively, it is called recursion. Recursion is of two types,

  • Direct Recursion Recursion in which the function calls itself is called ‘Direct recursion’. In this type only one function is involved.
  • Indirect recursion In this type two functions call each other.

e.g. int num() int num() { { … … int num(); int sum(); } } Direct recursion int sum() { … num(); } Indirect Recursion

Note: Recursion is one of the applications of stack. Two essential conditions should be satisfied by a recursive function.

  1. Every time a function should call itself directly or indirectly.
  2. a function should have a condition to stop the recursion, otherwise , an infinite loop is generated.

Rules for Recursive Function:

  1. In recursion , it is essential for a function to call itself, otherwise recursion will not take place.
  2. Only user defined functions can be involved in recursion.
  3. Library functions can not be involved in recursion because their source code cannot be viewed.
  4. The last-in-first-out nature of recursion indicates that stack data structure can be used to implement it.
  5. The user defined function main() can be invoked recursively. to implement such recursion it is necessary to mention prototype of function main().
  6. when a recursive function is executed, the recursion calls are not implemented instantly.

All the recursive calls are pushed onto the stack until the terminating condition is not detected.

As soon as the terminating condition is detected, the recursive calls stored in the stack are popped & executed.

The last call is executed first, then the second last, then the third last & so on..

  1. During recursion, at each recursive call new memory is allocated to all the local variables of the recursive functions with the same name.
  2. At each call the new memory is allocated to all the local variables, their previous values are pushed onto the stack with its call. All these values can be available to corresponding function call when it is popped from the stack.

Example 9: (mairec) Example 10: (refer cdatap\fact)

Recurion Vs. Iterations: We have studied both iterations & Recursion. They can be applied to a program depending upon the situation.

Recursion:

  1. Recursion is the term given to the mechanism of defining a set or procedure in terms of itself.
  2. (^) A conditional statement is required in the body of the function for stopping the function execution.
  3. Recursion is expensive in terms of memory & speed.

Iteration:

  1. The block of statement executed repeatedly using loops.
  2. The iteration control statement itself contains statement for stopping the iteration. At every execution, the condition is checked.
  3. All the programming language support iteration.

SORTING

Sorting is a process in which records are arranged in ascending or descending order. A group of fields is called a record. e.g. struct employee { char name[25]; int age; float height; }s;

The above declaration contains three fields as described in the structure. The database is a collection of such fields. The fields may vary depending upon the structure defined.

It is easy to understand but time consuming.

Note: Bubble sort is an example of exchange sort. e.g. consider the following list: 9 5 1 4 3 here 5 and 9 are compared 5 9 1 4 3 then swapping takes place 5 9 1 4 3 here 9 and 1 are compared 5 1 9 4 3 then swapping takes place 5 1 9 4 3 here 9 and 4 are compared 5 1 4 9 3 then swapping takes place 5 1 4 9 3 here 9 and 3 are compared 5 1 4 3 9 then swapping takes place This is pass 1 Next, 5 1 4 3 9 here 5 and 1 are compared 1 5 4 3 9 swapping takes place 1 5 4 3 9 here 5 and 4 are compared 1 4 5 3 9 swapping takes place 1 4 5 3 9 here 5 and 3 are compared 1 4 3 5 9 swapping takes place 1 4 3 5 9 here 5 and 9 are compared 1 4 3 5 9 F 0E 0pass 2

and so on…till the final sorted list 1 3 4 5 9

Quick Sort: It is also known as partition exchange sort. It was invented by CAR Hoare.

It is based on partition.

Hence the method falls under divide & conquer technique.

The main list of elements is divided into two sub-lists.

For example, a list of X elements are to be sorted.

The quick sort marks an element in a list called as pivot or key. consider the first element J as pivot.

Shift all the elements whose value is less than J towards the left & the elements whose value is greater than J to the right of J.

Now the key element divides the main list into two parts.

Note: It is not necessary that selected key element must be in the middle.

Any element from the list can act as key element.

Time consumption of the quick sort depends on the location of the key in the list.

Example 13: (refer qsort)

Merge sort: Merging is a process in which two lists are merged to form a new list.

The new list is sorted list. Before merging , individual lists are sorted and then merging is done. e.g. If we have the following numbers, 2 8 6 5 1 3 7 then , In merge sort , first the list is divided into pairs containing two elements each. This can be as follows 2 8 6 5 1 3 7 After division of the list into pairs, sort the elements of each pair.

2 8 5 6^ 1 3^7 Merger the pairs after sorting. 2 8 5 6 1 3 7 sort the elements of above merged pairs. 2 5 6 8 1 3 7 Again merge two groups

2 5 6 8 1 3 7 At last pass all elements gets sorted.

SEARCHING:

Searching is a technique of finding an element from the given data list or set of elements like an array, tree or list.

A record is quickly searched in a sorted database.

Assume a particular element n is to be searched.

The element ‘n’ is compared with all the elements in a list , starting from first element of the array till the last element.

The process of searching is continued till the element is found or list is completely exhausted.

The complexity of any searching method is determined from the number of comparisons performed.

There are three cases in which an element can be found. 1 In the best case, the element is found during the first comparison itself. 2 In the worst case, the element is found only in the last comparison.