SlideShare a Scribd company logo
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.
Ch 1 intriductions
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 %d\n&quot;,item,i+1); break; } } if (i == n) printf (&quot;\nItem %d not found in array\n&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;\n\nMemory 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;\n\nThe 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 memory\n”); exit(1); } strcpy( str,”Hello”); printf(“String is %s\n”,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 memory\n”); exit(1); } strcpy( str,”Hello”); printf(“String is %s\n”,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 %d\n”,str,str); str=(char *)realloc(str,40); strcpy( str,”System Design”); printf(“Address of String %s is %d\n”,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 ?

More Related Content

PDF
Data Structures & Algorithm design using C
PPT
linked list (c#)
PPTX
Data structure using c module 1
PPTX
C programming
PPT
Introduction of data structure
PPT
Basic data-structures-v.1.1
PPTX
Data Structure
PPTX
Data structure &amp; algorithms introduction
Data Structures & Algorithm design using C
linked list (c#)
Data structure using c module 1
C programming
Introduction of data structure
Basic data-structures-v.1.1
Data Structure
Data structure &amp; algorithms introduction

What's hot (20)

PPT
Data Structure In C#
PPTX
Data structures and algorithms
PPTX
Lecture 1 and 2
PPTX
Data structure using c module 3
PPTX
PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...
PPT
Data structures
PPT
Data structure lecture 2
PPT
Linked list
PPTX
Data structures
PPTX
Circular link list.ppt
PPT
Chapter 2.2 data structures
PPTX
Data structures and algorithms
PPTX
Data structure , stack , queue
PPTX
Array implementation and linked list as datat structure
PPT
Data structures
PDF
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
PDF
Unit ii data structure-converted
PPTX
Searching Algorithms
PPTX
Binary search
Data Structure In C#
Data structures and algorithms
Lecture 1 and 2
Data structure using c module 3
PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...
Data structures
Data structure lecture 2
Linked list
Data structures
Circular link list.ppt
Chapter 2.2 data structures
Data structures and algorithms
Data structure , stack , queue
Array implementation and linked list as datat structure
Data structures
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Unit ii data structure-converted
Searching Algorithms
Binary search
Ad

Viewers also liked (11)

PPTX
16 dynamic-memory-allocation
PPTX
C dynamic ppt
PPT
Memory allocation in c
PPTX
Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...
PPTX
Dynamic memory allocation in c++
PPSX
4 dynamic memory allocation
PDF
TLPI - 7 Memory Allocation
PDF
程式設計師的自我修養 Chapter 8
PPT
Memory allocation (4)
PPTX
Memory allocation for real time operating system
PDF
How to Become a Thought Leader in Your Niche
16 dynamic-memory-allocation
C dynamic ppt
Memory allocation in c
Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...
Dynamic memory allocation in c++
4 dynamic memory allocation
TLPI - 7 Memory Allocation
程式設計師的自我修養 Chapter 8
Memory allocation (4)
Memory allocation for real time operating system
How to Become a Thought Leader in Your Niche
Ad

Similar to Ch 1 intriductions (20)

PPTX
CSE 443 (1).pptx
PPTX
project on data structures and algorithm
PDF
L1803016468
PDF
Introduction to Data Structure
PDF
Data structure
PPTX
1.3 Linked List.pptx
DOCX
Datastructures and algorithms prepared by M.V.Brehmanada Reddy
PPTX
Introduction to data structures and its types
PDF
UNITIII LDS.pdf
PPTX
Data Structure Introduction- Arrays, Matrix, Linked List
DOCX
Data Structure Question Bank(2 marks)
PPTX
Data Structures in C
PPTX
Searching.pptx
PDF
DS Complete notes for Computer science and Engineering
PPTX
Data structures - Introduction
PPTX
Data structures in c#
PPTX
Data Structure
PDF
Data structure
PPTX
DATA STRUCTURES unit 1.pptx
PPTX
algorithm assignmenteeeeeee.pptx
CSE 443 (1).pptx
project on data structures and algorithm
L1803016468
Introduction to Data Structure
Data structure
1.3 Linked List.pptx
Datastructures and algorithms prepared by M.V.Brehmanada Reddy
Introduction to data structures and its types
UNITIII LDS.pdf
Data Structure Introduction- Arrays, Matrix, Linked List
Data Structure Question Bank(2 marks)
Data Structures in C
Searching.pptx
DS Complete notes for Computer science and Engineering
Data structures - Introduction
Data structures in c#
Data Structure
Data structure
DATA STRUCTURES unit 1.pptx
algorithm assignmenteeeeeee.pptx

Recently uploaded (20)

PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
master seminar digital applications in india
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
Pharma ospi slides which help in ospi learning
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Business Ethics Teaching Materials for college
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
Institutional Correction lecture only . . .
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PPTX
Cell Types and Its function , kingdom of life
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
STATICS OF THE RIGID BODIES Hibbelers.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
TR - Agricultural Crops Production NC III.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
O5-L3 Freight Transport Ops (International) V1.pdf
FourierSeries-QuestionsWithAnswers(Part-A).pdf
master seminar digital applications in india
Abdominal Access Techniques with Prof. Dr. R K Mishra
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
102 student loan defaulters named and shamed – Is someone you know on the list?
Pharma ospi slides which help in ospi learning
Microbial diseases, their pathogenesis and prophylaxis
Business Ethics Teaching Materials for college
2.FourierTransform-ShortQuestionswithAnswers.pdf
Institutional Correction lecture only . . .
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
Cell Types and Its function , kingdom of life
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx

Ch 1 intriductions

  • 1. 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
  • 2. 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
  • 3. 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.
  • 4. 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
  • 5. 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
  • 6. 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.
  • 7. 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
  • 8. 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. .
  • 9. Types of Linked Lists: Singly linked lists Circularly singly linked lists Doubly linked lists Circular doubly linked lists
  • 10. 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
  • 11. 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
  • 12. 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.
  • 14. 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.
  • 15. 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 .
  • 16. 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
  • 17. Lucknow Hyderabad Ahmadabad Chennai Mumbai New Delhi Above graph shows the cities for which there is a direct flight.
  • 18. 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.
  • 19. 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.
  • 20. 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.
  • 21. 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.
  • 22. 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) ”
  • 23. If there exists positive constants c and n 0 such that f(n)<=cg(n) for all values of n>n 0
  • 24. 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.
  • 26. 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
  • 27. 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.
  • 28. 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
  • 29. 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]
  • 30. 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).
  • 31. //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 %d\n&quot;,item,i+1); break; } } if (i == n) printf (&quot;\nItem %d not found in array\n&quot;,item); }
  • 32. 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
  • 33. 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
  • 34. 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 .
  • 35. C provides the following dynamic allocation and de-allocation functions : (i) malloc( ) (ii) calloc( ) (iii) realloc( ) (iv) free( )
  • 36. 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.
  • 37. 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
  • 38. 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));
  • 39. // 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;\n\nMemory 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;\n\nThe SUM of no(s) is = %d&quot;,sum); getch(); free(p); }
  • 40. malloc():An Example void main() { char *str; str=(char *)malloc(10*sizeof(char)) if(str==NULL) { printf(“Out of memory\n”); exit(1); } strcpy( str,”Hello”); printf(“String is %s\n”,str); free(str); }
  • 41. 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.
  • 42. 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
  • 43. calloc():An Example void main() { char *str = NULL; str=(char *)calloc(10,sizeof(char)); if(str==NULL) { printf(“Out of memory\n”); exit(1); } strcpy( str,”Hello”); printf(“String is %s\n”,str); free(str); }
  • 44. 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.
  • 45. 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
  • 46. 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.
  • 47. realloc():An Example void main() { char *str; str=(char *)malloc(10); strcpy( str,”Embedded”); printf(“Address of String %s is %d\n”,str,str); str=(char *)realloc(str,40); strcpy( str,”System Design”); printf(“Address of String %s is %d\n”,str,str); free(str); }
  • 48. 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.
  • 49. 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.
  • 50. 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()
  • 51. 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 .
  • 52. 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
  • 53. Dangling Pointer main() { int *a; a=(int*)malloc(sizeof(a)); *a=20; free(a); …… ; …… ; } 20 ?

Editor's Notes

  • #7: Summary and objectives…