• Save
Ch 1 intriductions
Upcoming SlideShare
Loading in...5
×
 

Ch 1 intriductions

on

  • 984 views

 

Statistics

Views

Total Views
984
Views on SlideShare
984
Embed Views
0

Actions

Likes
0
Downloads
0
Comments
1

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
  • very usefull presentation and very easy to understand
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • Summary and objectives…

Ch 1 intriductions Ch 1 intriductions Presentation Transcript

  • Data structure
    • A data structure is a way of storing  data  in a computer memory, so that it can be retrieved and manipulate efficiently.
    • It is an organization of mathematical and logical concepts of data.
    • The choice of particular data structure depends on following considerations
      • It must be able to represent the inherent (essential) relationship of data in the real world .
      • It must be simple enough, so that it can process efficiently, when necessary
    • The various types of data structure are divided in to fallowing categories.
    • Linear data structures:- A data structure whose elements form a sequence and every element in structure has a unique predecessor and unique successor.abc
    • Eg . array, linked list, stack, queues
    • b) Non-linear data structures:- A data structure whose elements do not form a sequence, there is no unique predecessor or unique successor.
    • Eg . Trees and graphs
    • Abstract Data type:- It refers to act of representing essential features without including background details or explanations.
    • 1. Arrays:- An array is a list of finite number of elements of same data type. The individual elements of an array are accessed using an index to the array.
      • If the number of elements is n in array, then the size of array would be n.
      • In general, if lb the smallest index, called lower bound, and ub largest index called upper bound , then the size of linear array is given by
      • size= ub – lb +1
    9 0 3 14 6 4 7 8
    • 2. Stacks
    • A stack is defined as a special type of data structure in which insertions and deletions can take place only at one end, called the top.
    • Stack is organized as a Last In First Out (LIFO) data structure.
    top Stack with 4 elements
  • 3-Queues
    • A queue is defined as a special type of data structure where the elements are inserted from one end and elements are deleted from the other end.
    • The end from where the elements are inserted is called REAR end.
    • The end from where the elements are deleted is called FRONT end .
    • Queue is organized as First In First Out (FIFO)Data Structure.
  • In a queue, the elements are always inserted at the rear end and deleted from the front end. Insert delete Front end Rear end 0 1 2 3 4 Pictorial representation of a Queue Queue 10 20 30
  • 4- Linked Lists
    • A linked list is a linear collection of data elements, called nodes.
    • Between, each node in the list, there exists a logical relationship
    • Each node is divide tow or more parts.
    • Each node can hold the data along with a pointer field using which address of the next node can be obtained.
    • .
    • Types of Linked Lists:
    • Singly linked lists
    • Circularly singly linked lists
    • Doubly linked lists
    • Circular doubly linked lists
    • Singly linked lists:- In single linked list each node
    • is divide in to two part
    • First part contain the information of the element.
    • Second part called nextpointer field, the address
    • of next node in the list.
    Next pointer field of first node Information field of first node
  • Circular singly linked list
    • Linear linked list containing the address of the first node in the link field of the last node results in a Circular Singly linked list or Circular list.
    last Pictorial representation of Circular singly linked list
    • Doubly linked lists
    • In double linked list each node divided three parts;
    • First part called previous pointer field, contains the address of preceding elements in the list.
    • Second part contain the information of the elements.
    • Third part called next pointer field, contains the address of succeeding elements in the list.
    • Circular doubly linked lists
    • Trees
    • A tree is a non-linear data structure that consists of a root node and potentially many levels of additional nodes that form a hierarchy.
    • Nodes that have no children are called leaf nodes
    • Non-root and non-leaf nodes are called internal nodes
    A tree data structure leaf nodes root node internal nodes Tree can represent inheritance relationship between classes.
    • Trees
    • A tree is data structure that represent a hierarchical relationship between various nodes.
    • Each node has zero or more child nodes ,
    • A child has at most one parent; a node without a parent is called the root node (or root ).
    • Nodes with no children are called leaf nodes .
    • Graphs
    • A graph is a mathematical structure consisting of a set of vertexes (also called nodes) and a set of edges. An edge is a pair of vertexes .
    • The two vertexes are called the edge endpoints .
    • They are used to model real-world systems such as the Internet, airline connections or a city road network
  • Lucknow Hyderabad Ahmadabad Chennai Mumbai New Delhi Above graph shows the cities for which there is a direct flight.
    • Common operations on data structures:- the various operations that can be performed on different data structures are
    • Traversing – Accessing each element exactly once in order to process it. This operation is called visiting the element.
    • Searching – find the location of the element with a given value.
    • Insertion – Adding a new element to the list.
    • Deletion – removing an element from list.
    • Sorting – arranging the elements in some logical order
    • Merging – combine the elements of two similar lists to a single list.
  • Introduction to Algorithms
    • An algorithms is a finite set of steps defining the solution of a particular problem.
    • An algorithm can be expressed in English like language, called pseudocode .
    • Algorithms are used for calculation , data processing , and many other fields.
    • Every algorithm must satisfy the following criteria:-
    • Input :- there are zero or more values which are externally supplied.
    • Output:- At least one value is produced.
    • Definiteness:- each steps must be clear and unambiguous (unmistakable).
    • Finiteness:- in every case Algorithm must terminate after a finite number of steps.
    • Effectiveness:- each steps must be feasible.
    • Complexity of Algorithm :- It refers to the rate at which the required storage or consumed time grows as a function of the problem size.
    • The absolute growth -depends on the machine used to execute the program.
      • SPACE COMPLEXITY:- The space complexity of an algorithm or program is the amount of memory it needs to run to completion.
      • TIME COMPLEXITY:- The time complexity of an algorithm or a program is the amount of time it needs to run to completion.
      • its depends on the amount of data inputted to an algorithm.
    • Big “OH” Notation:- it is a characteristic scheme that measures properties of algorithm complexity performance and/or memory requirements.
    • The space and/or time complexity is expressed in the form of a function f(n),
    • where n is input size.
    • The complexity function f(n) of an algorithm increases as ‘n’ increases.
    • Let , f(n) and g(n) are the functions defined on positive number then the function f(n)=O(g(n))
    • can be read as “ f (n) is of the order of g(n) ”
    • If there exists positive constants c and n 0 such that f(n)<=cg(n) for all values of n>n 0
    • When we analyze an algorithm it depends on the input data , there are three cases :
    • Worst case
    • Average case
    • Best case
    • Worst case , the maximum value of f(n) for any possible input.
    • Average case , the amount of time a program might be expected to take on typical (or average) input data.
    • Best case, the minimum possible value of f(n) for any possible input.
    • There is a theorem, which states that if
    • Based on the time complexity representation of the big Oh notation, the algorithm
    • can be categorized as :
        • 1 . Constant time O(1)
        • 2. Logarithmic time Olog(n)
        • 3. Linear time O(n)
        • 4. Polynomial time O(n c )
        • 5. Exponential time O(c n )
        • Where c > 1
    • Limitations of Big Oh Notation:-
    • It does not discuss the way and means to improve the efficiency of the program.
    • It does not exhibit (show) the potential of the constants
    • For example , one algorithm is taking 1000n 2 time to execute and the other n 3 time.
    • The first algorithm is O(n 2 ) ,which implies that it will take less time than the other algorithm which is O(n 3 ).
    • However in actual execution the second algorithm will be faster for n < 1000.
    • ALGORITHM FOR LINEAR SEARCH
    • Let A be an array of n elements, A[1],A[2],A[3], ...... A[n]. “ITEM” is the element to be searched. This algorithm will find the location “loc” of ITEM in A. Set loc = – 1,if the search is unsuccessful.
    • Input an array A of n elements and “ITEM” to be searched and initialise loc = – 1.
    • Initialise i = 0; and repeat through step 3 if (i < n) by incrementing i by one .
    • If (ITEM = A[i])
    • (a) loc = i
    • (b) GOTO step 4
    • 4 . If (loc > 0)
    • Display “ITEM is found and searching is successful”
    • 5. Else
    • Display “ITEM is not found and searching is unsuccessful”
    • 6. Exit
    • TIME COMPLEXITY
    • Time Complexity of the linear search is found by number of comparisons made in searching a record.
    • In the worst case the desired element is present in the n th (or last) position of the array, so n comparisons are made. f (n) = O(n).
    • In the Average case , the desired element is appear in the array, and equally likely to occur at any position in the A. the number of comparisons can be any numbers 1,2,3,….n, and the each number occurs with probability p=1/n
    • then f (n) = 1.1/n+2.1/n+3.1/n+……..+n.1/n
    • =(1+2+3+………+n).1/n
    • =[(n(n+1))/2] .1/n= (n+1) /2
    • f (n) =O[(n + 1)/2]
    • In the best case , the desired element is present in the first position of the array, i.e., only one comparison is made. So f (n) = O(1).
    • //PROGRAM TO IMPLEMENT LINEAR OR SEQUENTIAL SEARCHING
    • #include<conio.h>
    • #include<stdio.h>
    • main()
    • { char opt;
    • int arr[20],n,i,item;
    • printf (&quot;nHow many elements you want to enter in the array : &quot;);
    • scanf (&quot;%d&quot;,&n);
    • for(i=0; i < n;i++)
    • {
    • printf (&quot;nEnter element %d : &quot;,i+1);
    • scanf (&quot;%d&quot;, &arr[i]);
    • }
    • printf (&quot;nEnter the element to be searched : &quot;);
    • scanf (&quot;%d&quot;,&item); //Input the item to be searched
    • for(i=0;i < n;i++)
    • {
    • if (item == arr[i])
    • {
    • printf (&quot;n%d found at position %dn&quot;,item,i+1);
    • break;
    • }
    • }
    • if (i == n)
    • printf (&quot;nItem %d not found in arrayn&quot;,item);
    • }
  • MEMORY ALLOCATION IN C
    • There are two types of memory allocations in C:
      • 1. Static memory allocation or Compile time
      • 2. Dynamic memory allocation or Run time
    • Static Memory Allocation
    • In static or compile time memory allocations , the required memory is allocated to the variables at the beginning of the program.
    • The allocated memory space cannot be expanded to accommodate more data or cannot be reduced to accommodate less data.
    • The memory space allocated is fixed and we cannot alter the size of the allocated space any time during execution.
    • For example
    • int i, j; //Two bytes per (total 2) integer variables
    • float a[5], f ; //Four bytes per (total 6) floating point variables
  • 2. Dynamic memory allocation or Run time
    • Dynamic memory allocation is the process of allocating memory space during rum time .
    • It makes efficient use of memory by allocating the required amount of memory whenever is needed.
    • It is a unique feature in C.
    • In situations, where there is an unpredictable storage requirement, this technique is very useful .
    • C provides the following dynamic allocation and de-allocation functions :
    • (i) malloc( ) (ii) calloc( )
    • (iii) realloc( ) (iv) free( )
  • malloc()
    • The function allocates and reserves a block of memory, specified in bytes and returns a pointer to the first byte of allocated space.
    • It reserves a block of memory by allocating specified number of bytes from the availability list(i.e from heap).
    • It allocates a block of contiguous bytes.
  • malloc():Syntax ptr = (data_type*)malloc(size); ptr is a pointer variable of type data_type data_type can be any of the basic data type or user defined data type size is the number of bytes required
    • Similarly, memory can be allocated to structure variables. For example
      • struct Employee
      • {
      • int Emp_Code;
      • char Emp_Name[50];
      • float Emp_Salary;
      • };
    • Here the structure is been defined with three variables.
    • struct Employee *ptr;
    • ptr = (struct Employee *) malloc(sizeof (struct Employee));
    • // PROGRAM TO FIND THE SUM OF n ELEMENTS USING DYNAMIC MEMORY ALLOCATION
    • #include<stdio.h>
    • #include<conio.h>
    • #define NULL 0
    • void main()
    • { int i=1,n,sum=0, *p,*q;
    • printf(&quot;nEnter the number of the element(s) to be added = &quot;);
    • scanf(&quot;%d&quot;,&n); //Enter the number of elements
    • p=(int *)malloc(n*sizeof(int)); //Allocating memory space
    • if(p == NULL)
    • {
    • printf(&quot;nnMemory allocation is failed&quot;);
    • exit(0);
    • }
    • for(q=p;q<(p+n);q++)
    • {
    • printf(&quot;Enter the %d element = &quot;,i++);
    • scanf(&quot;%d&quot;,q);
    • }
    • for(q=p;q<(p+n);q++)
    • sum=sum+(*q);
    • printf(&quot;nnThe SUM of no(s) is = %d&quot;,sum);
    • getch(); free(p); }
  • malloc():An Example void main() { char *str; str=(char *)malloc(10*sizeof(char)) if(str==NULL) { printf(“Out of memoryn”); exit(1); } strcpy( str,”Hello”); printf(“String is %sn”,str); free(str); }
  • calloc()
    • The function allocates multiple blocks of same size,initializes all locations to zero and returns a pointer to the first byte of the allocated space.
    • It allocates a block of contiguous bytes.
    • If the specified size of memory is not available, the function returns a NULL.
  • calloc():Syntax ptr = (data_type*)calloc(n,size); ptr is a pointer variable of type data_type data_type can be any of the basic data type or user defined data type size is the number of bytes required ‘ n’ is the number of blocks to be allocated if size bytes
  • calloc():An Example void main() { char *str = NULL; str=(char *)calloc(10,sizeof(char)); if(str==NULL) { printf(“Out of memoryn”); exit(1); } strcpy( str,”Hello”); printf(“String is %sn”,str); free(str); }
  • realloc()
    • This function is used to alter the size of the previously allocated space which is allocated either by using malloc or calloc functions.
    • This function guarantees that reallocating the memory will not destroy the original contents of memory.
    • The contents of the old block will be copied into a newly allocated space and so,this function guarantees that the earlier contents are not lost.
  • realloc():Syntax ptr = (data_type*)realloc(ptr,size); The address of the newly allocated memory after reallocation data_type can be any of the basic data type or user defined data type size is the number of bytes required for reallocation Starting address of allocated memory obtained previously
  • realloc():Return Value
    • On success, the function returns the address of reallocated block of memory.
    • If reallocation fails or if size specified is zero, the function return NULL and the original block is freed.
  • realloc():An Example void main() { char *str; str=(char *)malloc(10); strcpy( str,”Embedded”); printf(“Address of String %s is %dn”,str,str); str=(char *)realloc(str,40); strcpy( str,”System Design”); printf(“Address of String %s is %dn”,str,str); free(str); }
  • free()
    • This function is used to release the memory space that has been allocated earlier.
    • This function de-allocates the allocated block of memory which is allocated by using the functions malloc,calloc and realloc.
    • It is the responsibility of the programmer to de-allocate memory whenever it is not require by the application.
  • free():Syntax and Return Value free(ptr); ptr is a pointer to a memory block which has already been created
    • There is no return value for the free() function.
  • Differences:malloc() & calloc()
    • The syntax of malloc is ptr=(data_type*)malloc(size);
    • Allocates a contiguous block of memory of specified size.
    • Allocated space will not be initialized.
    • Time efficiency is higher than calloc().
    • The syntax of calloc is ptr=(data_type*)calloc(n,size);
    • Allocates multiple blocks of memory,each block with the same size.
    • Each byte of allocated space is initialized to zero.
    • It is more expensive in time efficiency because of zero initialization.
    malloc() calloc()
  • Memory Leakage main() { int *a; a=(int*)malloc(sizeof(int)); *a=10; a=(int*)malloc(sizeof(int)); *a=20; } 10 20
    • Allocation of memory is done twice.In this case, a contains the address of the most recently allocated memory.
    • The earlier allocated memory remains inaccessable.
    • The problem where in memory is reserved but not accessible to any application is called MEMORY LEAKAGE .
  • Dangling Pointer
    • Any pointer pointing to a destroyed object or which does not contain a valid address is called a Dangling Pointer.
    • If any pointer is pointing the memory address of any variable but after some time variable has deleted from that memory location while pointer is still pointing such memory location. Such pointer is known as dangling pointer and this problem is known as dangling pointer problem.
    Initially Latter
  • Dangling Pointer main() { int *a; a=(int*)malloc(sizeof(a)); *a=20; free(a); …… ; …… ; } 20 ?