SlideShare uma empresa Scribd logo
1 de 59
Data Structures

   Introduction
      Stacks
      Queues
       Trees
    Linked List
      Sorting
Chapter 01: Introduction
What is Data Structure?
• A data structure is a structured set of variables
  associated with one another in different ways,
  cooperatively defining components in the system and
  capable of being operated upon in the program.

• The following operations are done on data structures:
   – Data organization or clubbing
   – Accessing technique
   – Manipulating selections for information.

• In computer science, data structure is a way of storing
  data in a computer so it can be stored efficiently
Types of Data Structures
                                   DATA STRUCTURE




         LINEAR                                             NON-LINEAR




                                                    TREES
ARRAYS             STACK



                           QUEUE                                  GRAPH



         LINKED LIST
Types of Data Structures
• Data structures are classified into two main categories linear and non-
  linear.

• A data is said to linear if its elements form a sequence.

• An array is a finite collection of similar elements stored in adjacent
  memory locations.

• Linked list is a collection of elements called nodes each of which stores
  two items one information and the other a link to the next element.

• A stack is a data structure in which addition of new elements or deletion
  of old elements takes place at same end called top of stack.

• Queue is a linear data structure that permits insertion of new elements
  takes place at one end and deletion of elements takes place at other end.
Types of Data Structures
• Elements in a data structure which do not form a
  sequence are called as non-linear data structure.

• When any two vertices are connected by exactly one
  path is called as tree.

• Forest can be defined as any two vertices connected by
  at most one path.

• A graph can be defined as a set of dots (vertices and
  nodes) joined by lines (the edges)
Chapter 02: Stacks
Introduction
Various types of stack
Stack
• A stack is a data structure in which addition of new elements and
  deletion of old elements always takes place at same end known as
  top of stack

• Stack is one of the most useful concepts which play a permanent
  role in programming.

• In stack he last item to be inserted will be the first to be removed.

• This is why stack is referred to as LAST IN FIRST OUT [LIFO].

• If there are no items in stack then it is called as empty stack.
Empty stack
Stack operations
Stack Operations
• We can insert or delete an element from a list,
  which takes place from one end.

• When an item is added to the stack the operation
  is called "push" and when it is removed the
  operation is called "pop".

• Due to the push operation from one end,
  elements are added to the stack, the stack is also
  known as pushdown list.
Stack Operations
• The following fundamental operations on stack:
  –   Creating a stack
  –   Checking stack—either empty or full
  –   Initializing a stack
  –   Insert (push) an element in the stack
  –   Delete (pop) an element from the stack
  –   Access the top element (peek)
  –   Display elements of stack
  –   Status: to identify present position of stack.
Stack Algorithm – Adding Elements
• Variables: int size=10, top=-1;
            Object stack[10];

• Proc: void push(Object item)
• begin
    if top is equal to size
        then display stack_full;
    else
    top = top+1;
    stack[top] = item;
  end
Stack – Removing Elements
• Variables: int size=10, top=-1;
            Object stack[10];

• Proc: Object pop()
• begin
    if top is equal to -1
        then stack_empty;
    else
      item = stack[top];
      top = top-1;
  end
Stack Application
• Evaluation of arithmetic expressions.
   – Infix to postfix conversion
   – Evaluating arithmetic expressions

• Runtime memory management.

• Solving search problems.

• Calling subroutine.

• Syntax parsing.

• Reversing of string
Infix to Postfix conversion
• Rules
   – If incoming operator has more precedence than top of stack
     than push operator into stack.
   – If incoming operator has less or equal precedence than top of
     stack than operator is popped and incoming operator is pushed.
   – If we encounter a right parenthesis “)”, keep performing pop
     from the stack until we get matching left parenthesis. Do not
     output parenthesis.

• HIGHEST PRIORITY: exponentiation ($, ^)
• MIDDLE PRIORITY: multiply (*) and divide (/)
• LOWEST PRIORITY: addition (+) and subtraction (-)
Infix to Postfix Example
                           A + B * C - D / E

Infix                        Stack(bot->top)                   Postfix
 A + B * C -   D   /   E
   + B * C -   D   /   E                       A
     B * C -   D   /   E          +            A
       * C -   D   /   E          +            A   B
         C -   D   /   E          +   *        A   B
           -   D   /   E          +   *        A   B   C
               D   /   E          +   -        A   B   C   *
                   /   E          +   -        A   B   C   *   D
                       E          +   - /      A   B   C   *   D
                                  +   - /      A   B   C   *   D E
                                               A   B   C   *   D E / - +
Postfix Evaulation
Operand: push
Operator: pop 2 operands, do the math, push result
          back onto stack

                     1 2 3 + *

Postfix                 Stack( bot -> top )
a) 1 2 3 + *
b)    2 3 + *          1
c)      3 + *          1 2
d)        + *          1 2 3
e)          *          1 5   // 5 from 2 + 3
f)                     5     // 5 from 1 * 5
Chapter 03: Queue & Circular Queue
Introduction
• Queue is a linear data structure that permits insertion of a
  new element at one end and deletion of element at the
  other end.

• The end at which deletion of element takes place is known
  as FRONT and the end at which addition of new elements
  takes place is known as REAR.

• The first element that gets added into queue is the first to
  get deleted.

• Hence queue is also referred to as FIFO list First In First
  Out.
Queue Operations
• Insertion – adding elements to the queue.
• Deletion – removing elements from the
  queue.
Adding elements in queue
• Variables: int size=10, front=0, rear=-1;
            Object stack[10];

• Proc: void add(Object item)

• begin
    if rear is equal to n
        then queue_full
    else begin
        rear :=rear+1;
        q[rear]:=item;
    end;
  end
Deleting elements from queue
• begin
    if front = rear then queue_empty
    else begin
        front := front+1
        item := q[front];
    end;
  end;
Chapter 04: Linked List
Introduction
• Alternate approach to maintaining an array of
  elements

• Rather than allocating one large group of elements,
  allocate elements as needed

• Q: how do we know what is part of the array?
   A: have the elements keep track of each other
   – use pointers to connect the elements together as a LIST of
     things
Linked List
• A linked list is a series of connected nodes
• Each node contains at least
  – A piece of data (any type)
  – Pointer to the next node in the list
• Head: pointer to the first node
• The last node points to NULL
Linked List

       A          B                C

Head




           node
                   A

                  data   pointer
Chapter 05: Sorting
Introduction
• A sorting algorithm is an algorithm that puts
  elements of a list in a certain order.

• Some of the sorting techniques are:
  – Selection sort
  – Bubble sort
  – Quick sort
  – Merge sort
Selection Sort

• In this method to sort data in ascending order the 0th element is
  compared with all the other elements.

• If the 0th element is found to be greater than the compared
  element then they are interchanged.

• So after the first iteration the smallest element is placed at the 0th
  position.

• The same procedure is repeated for the first element and so on.

• So if there are n elements than after n-1 iterations the array
  becomes sorted.
Selection Sort - Algorithm
FOR (I=0; I<=N-1; I++)
               {
                 FOR (J=I+1; J<=N; J++)
                       {
                          IF (ARR [I]>ARR [J])
                              {
                                  TEMP=ARR [I];
                                  ARR [I] =ARR [J];
                                  ARR [J] =TEMP;
                                }
                         }
                   }
Bubble Sort
• In this method to sort data in ascending order the 0th element is compared
  with the 1st element.

• If found to b greater than the positions are interchanged.

• Than the 1st element is compared with the 2nd element if found to be
  greater than they are interchanged.

• In the same way all elements except the last are compared with the next
  element and interchanged if required.

• This is the 1st iteration and on completion the largest gets stored at the
  last position.

• As a result after all iterations the list becomes a sorted list.

• If there are n elements than after n-1 iterations the array becomes sorted
Bubble Sort – Algorithm
FOR (I=0; I<=N-1; I++)
                         {
                             FOR (J=0; J<N-1-I; J++)
                                 {
                                   IF (ARR [I]>ARR [J])
                                       {
                                         TEMP=ARR [I];
                                         ARR [I] =ARR [J];
                                         ARR [J] =TEMP;
                                       }
                                }
                         }
Quick Sort
• This algorithm is based on the fact that it is easier and
  faster to sort two small arrays than one large one.

• The basic strategy of quick sort is to divide and
  conquer.

• Quick sort is also known as partition exchange sort.

• Quick sort may be defined conveniently by using
  recursive procedure
Quick Sort
• The basic divide-and-conquer process for sorting a subarray
  S[p..r] is summarized in the following three easy steps:

  Divide: Partition S[p..r] into two subarrays S[p..q-1] and S[q+1..r]
  such that each element of S[p..q-1] is less than or equal to S[q],
  which is, in turn, less than or equal to each element of S[q+1..r].
  Compute the index q as part of this partitioning procedure

  Conquer: Sort the two subarrays S[p...q-1] and S[q+1..r] by
  recursive calls to quicksort.

  Combine: Since the subarrays are sorted in place, no work is
  needed to combing them: the entire array S is now sorted.
Quick Sort
• The divide-and-conquer strategy is used in quicksort. Below the
  recursion step is described:

• Choose a pivot value. We take the value of the middle element as
  pivot value, but it can be any value, which is in range of sorted
  values, even if it doesn't present in the array.

• Partition. Rearrange elements in such a way, that all elements
  which are lesser than the pivot go to the left part of the array and
  all elements greater than the pivot, go to the right part of the array.
  Values equal to the pivot can stay in any part of the array. Notice,
  that array may be divided in non-equal parts.

• Sort both parts. Apply quicksort algorithm recursively to the left
  and the right parts.
Merge Sort
• Merging means combining two sorted lists into one list.

• For this the elements from both the sorted lists are
  compared.

• The smaller of both the elements is than sorted in the
  third array.

• The sorting s complete when all the elements from
  both the lists are placed in the third list.
Merge Sort
•   Suppose array a & b contain 5 elements each. Than merge sort algorithm
    works as follows:

•   The arrays a & b are sorted using any algorithm

•   The 0th element from 1st array is compared with the 0th element in the 2nd
    array. The smaller of the two is placed in the 3rd array.

•   Now the biggest of them is compared with the 1st element of the other array.

•   The smaller of the two is placed in the third array.

•   The same procedure is repeated till end of one of the arrays is reached.

•   The remaining elements from the other array are placed directly into the third
    list as they are already in the sorted order.
Merge Sort – Algorithm
• To sort the entire sequence A[1 .. n], make the initial call to
  the procedure MERGE-SORT (A, 1, n).

• MERGE-SORT (A, p, r)
  1. IF p < r                                // Check for base
  2.    THEN q = FLOOR[(p + r)/2]               // Divide step
  3.         MERGE (A, p, q)                  // Conquer step.
  4.         MERGE (A, q + 1, r)               // Conquer step.
  5.         MERGE (A, p, q, r)                // Conquer step.
Chapter 06: Searching
Introduction
• Searching is an operation which finds the
  location of a given element in a list.

• The search is said to be successful or
  unsuccessful depending on whether the
  element that is being searched for is found or
  not.
Linear Search
• This is the simplest method of searching.
• In this method the element to be found is sequentially
  searched in the list.
• This method can be applied to a sorted or an unsorted
  array.
• Searching in case of a sorted list starts from the 0th
  element and continues until the element is found or an
  element whose value is greater than the value being
  searched is reached.
• Searching in case of an unsorted list starts from 0th
  element and continues until element is found or end or
  list is reached
Unsorted List – Linear Search
FOR (I=0; I<N-1;I++)
       {
         IF (ARR [ I ] = = NUM)
         BREAK
       }
IF (I = = 10)
    PRINT (NO. NOT PRESENT)
ELSE
    PRINT (NO. PRESENT)
Sorted List – Linear Search
FOR (I=0; I<N-1;I++)
    {
      IF (ARR [9] < NUM | | ARR [I] >= NUM)
          {
             IF (ARR [I] = = NUM)
                  PRINT (PRESENT)
              ELSE
                   PRINT (ABSCENT)
             BREAK
           }
     }
Binary Search

– This method is very fast and efficient.

– This search requires the list of elements to be in sorted
  order.

– In this method to search for an element we compare with
  the element present at the centre of the list.

– If it matches than the search is successful.
Binary Search
– Otherwise the list is divided into two halves:

– One from the 0th element to the centre of the list.

– The other from the centre to the end of the list.

– As a result all the elements in the first half are smaller than the centre
  element whereas all elements in the second half are greater than the center
  element.

– The searching will now precede in either of t he two halves depending on
  whether the element is greater or smaller than the middle element.

– Same process of comparing the center element and then dividing the array is
  repeated for the first or second half.

– This process is repeated till element is found or division results in one element
Binary Search – Algorithm
WHILE (NOT END OF INPUT)
     {
       LOW = 0
       HI = N-1

         WHILE (LOW<= HI)
               {
                 MID = (LOW + HI) / 2

                    IF (KEY = = K [MID])
                        RETURN MID

                    IF (KEY < K [MID])
                        HI = MID – 1

                ELSE
                        LOW = MID + 1
                }
     }
Chapter 07: Binary Tree
Introduction
• Definition: A binary tree, T, is either empty or
  such that:
  – T has a special node called the root node;
  – T has two sets of nodes, LT and RT, called the left
    subtree and right subtree of T, respectively;
  – LT and RT are binary trees
Binary Tree
Binary Tree - Terms
• Leaf: node that has no left and right children

• Parent: node with at least one child node

• Level of a node: number of branches on the path
  from root to node

• Height of a binary tree: number of nodes no the
  longest path from root to node
Binary Tree – Traversal
• Inorder
  – Traverse the left subtree
  – Visit the node
  – Traverse the right subtree
• Preorder
  – Visit the node
  – Traverse the left subtree
  – Traverse the right subtree
• Postorder
  – Traverse the left subtree
  – Traverse the right subtree
  – Visit the node
Data structures

Mais conteúdo relacionado

Mais procurados (20)

Array data structure
Array data structureArray data structure
Array data structure
 
Queue ppt
Queue pptQueue ppt
Queue ppt
 
queue & its applications
queue & its applicationsqueue & its applications
queue & its applications
 
Linked list
Linked listLinked list
Linked list
 
sorting and its types
sorting and its typessorting and its types
sorting and its types
 
Data structure & its types
Data structure & its typesData structure & its types
Data structure & its types
 
Tree - Data Structure
Tree - Data StructureTree - Data Structure
Tree - Data Structure
 
Stacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESStacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURES
 
Sets in python
Sets in pythonSets in python
Sets in python
 
STACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data StructureSTACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data Structure
 
1.1 binary tree
1.1 binary tree1.1 binary tree
1.1 binary tree
 
Sparse matrix and its representation data structure
Sparse matrix and its representation data structureSparse matrix and its representation data structure
Sparse matrix and its representation data structure
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
 
Data Structure (Queue)
Data Structure (Queue)Data Structure (Queue)
Data Structure (Queue)
 
linked lists in data structures
linked lists in data structureslinked lists in data structures
linked lists in data structures
 
Data Structures
Data StructuresData Structures
Data Structures
 
Heap and heapsort
Heap and heapsortHeap and heapsort
Heap and heapsort
 
Deque and its applications
Deque and its applicationsDeque and its applications
Deque and its applications
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
 
Data structure stack&queue basics
Data structure stack&queue   basicsData structure stack&queue   basics
Data structure stack&queue basics
 

Semelhante a Data structures

Semelhante a Data structures (20)

Ist year Msc,2nd sem module1
Ist year Msc,2nd sem module1Ist year Msc,2nd sem module1
Ist year Msc,2nd sem module1
 
Ds stack & queue
Ds   stack & queueDs   stack & queue
Ds stack & queue
 
Queues
Queues Queues
Queues
 
Data Structures
Data StructuresData Structures
Data Structures
 
DS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptxDS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptx
 
Revisiting a data structures in detail with linked list stack and queue
Revisiting a data structures in detail with linked list stack and queueRevisiting a data structures in detail with linked list stack and queue
Revisiting a data structures in detail with linked list stack and queue
 
2.1 STACK & QUEUE ADTS
2.1 STACK & QUEUE ADTS2.1 STACK & QUEUE ADTS
2.1 STACK & QUEUE ADTS
 
Stack and Queue.pptx
Stack and Queue.pptxStack and Queue.pptx
Stack and Queue.pptx
 
Data structures and Algorithm analysis_Lecture 2.pptx
Data structures and Algorithm analysis_Lecture 2.pptxData structures and Algorithm analysis_Lecture 2.pptx
Data structures and Algorithm analysis_Lecture 2.pptx
 
Stack in Sata Structure
Stack in Sata StructureStack in Sata Structure
Stack in Sata Structure
 
Stacks
StacksStacks
Stacks
 
LEC4-DS ALGO.pdf
LEC4-DS  ALGO.pdfLEC4-DS  ALGO.pdf
LEC4-DS ALGO.pdf
 
queue.pptx
queue.pptxqueue.pptx
queue.pptx
 
Data structures
Data structuresData structures
Data structures
 
VCE Unit 03vv.pptx
VCE Unit 03vv.pptxVCE Unit 03vv.pptx
VCE Unit 03vv.pptx
 
data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3
 
DS UNIT2QUEUES.pptx
DS UNIT2QUEUES.pptxDS UNIT2QUEUES.pptx
DS UNIT2QUEUES.pptx
 
1.Introduction to Data Structures and Algorithms.pptx
1.Introduction to Data Structures and Algorithms.pptx1.Introduction to Data Structures and Algorithms.pptx
1.Introduction to Data Structures and Algorithms.pptx
 
10994103.ppt
10994103.ppt10994103.ppt
10994103.ppt
 
DS UNIT 1.pdf
DS UNIT 1.pdfDS UNIT 1.pdf
DS UNIT 1.pdf
 

Mais de Sneha Chopra

Mais de Sneha Chopra (8)

Embedded System
Embedded SystemEmbedded System
Embedded System
 
E.s unit 6
E.s unit 6E.s unit 6
E.s unit 6
 
E.s unit 4 and 5
E.s unit 4 and 5E.s unit 4 and 5
E.s unit 4 and 5
 
E.s (2)
E.s (2)E.s (2)
E.s (2)
 
Computer Graphics
Computer GraphicsComputer Graphics
Computer Graphics
 
Rad model
Rad modelRad model
Rad model
 
Multimedia
MultimediaMultimedia
Multimedia
 
Modern Operating System Windows Server 2008
Modern Operating System  Windows Server 2008Modern Operating System  Windows Server 2008
Modern Operating System Windows Server 2008
 

Data structures

  • 1. Data Structures Introduction Stacks Queues Trees Linked List Sorting
  • 3. What is Data Structure? • A data structure is a structured set of variables associated with one another in different ways, cooperatively defining components in the system and capable of being operated upon in the program. • The following operations are done on data structures: – Data organization or clubbing – Accessing technique – Manipulating selections for information. • In computer science, data structure is a way of storing data in a computer so it can be stored efficiently
  • 4. Types of Data Structures DATA STRUCTURE LINEAR NON-LINEAR TREES ARRAYS STACK QUEUE GRAPH LINKED LIST
  • 5. Types of Data Structures • Data structures are classified into two main categories linear and non- linear. • A data is said to linear if its elements form a sequence. • An array is a finite collection of similar elements stored in adjacent memory locations. • Linked list is a collection of elements called nodes each of which stores two items one information and the other a link to the next element. • A stack is a data structure in which addition of new elements or deletion of old elements takes place at same end called top of stack. • Queue is a linear data structure that permits insertion of new elements takes place at one end and deletion of elements takes place at other end.
  • 6. Types of Data Structures • Elements in a data structure which do not form a sequence are called as non-linear data structure. • When any two vertices are connected by exactly one path is called as tree. • Forest can be defined as any two vertices connected by at most one path. • A graph can be defined as a set of dots (vertices and nodes) joined by lines (the edges)
  • 10. Stack • A stack is a data structure in which addition of new elements and deletion of old elements always takes place at same end known as top of stack • Stack is one of the most useful concepts which play a permanent role in programming. • In stack he last item to be inserted will be the first to be removed. • This is why stack is referred to as LAST IN FIRST OUT [LIFO]. • If there are no items in stack then it is called as empty stack.
  • 13. Stack Operations • We can insert or delete an element from a list, which takes place from one end. • When an item is added to the stack the operation is called "push" and when it is removed the operation is called "pop". • Due to the push operation from one end, elements are added to the stack, the stack is also known as pushdown list.
  • 14. Stack Operations • The following fundamental operations on stack: – Creating a stack – Checking stack—either empty or full – Initializing a stack – Insert (push) an element in the stack – Delete (pop) an element from the stack – Access the top element (peek) – Display elements of stack – Status: to identify present position of stack.
  • 15. Stack Algorithm – Adding Elements • Variables: int size=10, top=-1; Object stack[10]; • Proc: void push(Object item) • begin if top is equal to size then display stack_full; else top = top+1; stack[top] = item; end
  • 16. Stack – Removing Elements • Variables: int size=10, top=-1; Object stack[10]; • Proc: Object pop() • begin if top is equal to -1 then stack_empty; else item = stack[top]; top = top-1; end
  • 17. Stack Application • Evaluation of arithmetic expressions. – Infix to postfix conversion – Evaluating arithmetic expressions • Runtime memory management. • Solving search problems. • Calling subroutine. • Syntax parsing. • Reversing of string
  • 18. Infix to Postfix conversion • Rules – If incoming operator has more precedence than top of stack than push operator into stack. – If incoming operator has less or equal precedence than top of stack than operator is popped and incoming operator is pushed. – If we encounter a right parenthesis “)”, keep performing pop from the stack until we get matching left parenthesis. Do not output parenthesis. • HIGHEST PRIORITY: exponentiation ($, ^) • MIDDLE PRIORITY: multiply (*) and divide (/) • LOWEST PRIORITY: addition (+) and subtraction (-)
  • 19. Infix to Postfix Example A + B * C - D / E Infix Stack(bot->top) Postfix A + B * C - D / E + B * C - D / E A B * C - D / E + A * C - D / E + A B C - D / E + * A B - D / E + * A B C D / E + - A B C * / E + - A B C * D E + - / A B C * D + - / A B C * D E A B C * D E / - +
  • 20. Postfix Evaulation Operand: push Operator: pop 2 operands, do the math, push result back onto stack 1 2 3 + * Postfix Stack( bot -> top ) a) 1 2 3 + * b) 2 3 + * 1 c) 3 + * 1 2 d) + * 1 2 3 e) * 1 5 // 5 from 2 + 3 f) 5 // 5 from 1 * 5
  • 21. Chapter 03: Queue & Circular Queue
  • 22. Introduction • Queue is a linear data structure that permits insertion of a new element at one end and deletion of element at the other end. • The end at which deletion of element takes place is known as FRONT and the end at which addition of new elements takes place is known as REAR. • The first element that gets added into queue is the first to get deleted. • Hence queue is also referred to as FIFO list First In First Out.
  • 23. Queue Operations • Insertion – adding elements to the queue. • Deletion – removing elements from the queue.
  • 24. Adding elements in queue • Variables: int size=10, front=0, rear=-1; Object stack[10]; • Proc: void add(Object item) • begin if rear is equal to n then queue_full else begin rear :=rear+1; q[rear]:=item; end; end
  • 25. Deleting elements from queue • begin if front = rear then queue_empty else begin front := front+1 item := q[front]; end; end;
  • 27. Introduction • Alternate approach to maintaining an array of elements • Rather than allocating one large group of elements, allocate elements as needed • Q: how do we know what is part of the array? A: have the elements keep track of each other – use pointers to connect the elements together as a LIST of things
  • 28. Linked List • A linked list is a series of connected nodes • Each node contains at least – A piece of data (any type) – Pointer to the next node in the list • Head: pointer to the first node • The last node points to NULL
  • 29. Linked List A B C Head node A data pointer
  • 31. Introduction • A sorting algorithm is an algorithm that puts elements of a list in a certain order. • Some of the sorting techniques are: – Selection sort – Bubble sort – Quick sort – Merge sort
  • 32. Selection Sort • In this method to sort data in ascending order the 0th element is compared with all the other elements. • If the 0th element is found to be greater than the compared element then they are interchanged. • So after the first iteration the smallest element is placed at the 0th position. • The same procedure is repeated for the first element and so on. • So if there are n elements than after n-1 iterations the array becomes sorted.
  • 33. Selection Sort - Algorithm FOR (I=0; I<=N-1; I++) { FOR (J=I+1; J<=N; J++) { IF (ARR [I]>ARR [J]) { TEMP=ARR [I]; ARR [I] =ARR [J]; ARR [J] =TEMP; } } }
  • 34.
  • 35. Bubble Sort • In this method to sort data in ascending order the 0th element is compared with the 1st element. • If found to b greater than the positions are interchanged. • Than the 1st element is compared with the 2nd element if found to be greater than they are interchanged. • In the same way all elements except the last are compared with the next element and interchanged if required. • This is the 1st iteration and on completion the largest gets stored at the last position. • As a result after all iterations the list becomes a sorted list. • If there are n elements than after n-1 iterations the array becomes sorted
  • 36. Bubble Sort – Algorithm FOR (I=0; I<=N-1; I++) { FOR (J=0; J<N-1-I; J++) { IF (ARR [I]>ARR [J]) { TEMP=ARR [I]; ARR [I] =ARR [J]; ARR [J] =TEMP; } } }
  • 37.
  • 38. Quick Sort • This algorithm is based on the fact that it is easier and faster to sort two small arrays than one large one. • The basic strategy of quick sort is to divide and conquer. • Quick sort is also known as partition exchange sort. • Quick sort may be defined conveniently by using recursive procedure
  • 39. Quick Sort • The basic divide-and-conquer process for sorting a subarray S[p..r] is summarized in the following three easy steps: Divide: Partition S[p..r] into two subarrays S[p..q-1] and S[q+1..r] such that each element of S[p..q-1] is less than or equal to S[q], which is, in turn, less than or equal to each element of S[q+1..r]. Compute the index q as part of this partitioning procedure Conquer: Sort the two subarrays S[p...q-1] and S[q+1..r] by recursive calls to quicksort. Combine: Since the subarrays are sorted in place, no work is needed to combing them: the entire array S is now sorted.
  • 40. Quick Sort • The divide-and-conquer strategy is used in quicksort. Below the recursion step is described: • Choose a pivot value. We take the value of the middle element as pivot value, but it can be any value, which is in range of sorted values, even if it doesn't present in the array. • Partition. Rearrange elements in such a way, that all elements which are lesser than the pivot go to the left part of the array and all elements greater than the pivot, go to the right part of the array. Values equal to the pivot can stay in any part of the array. Notice, that array may be divided in non-equal parts. • Sort both parts. Apply quicksort algorithm recursively to the left and the right parts.
  • 41.
  • 42. Merge Sort • Merging means combining two sorted lists into one list. • For this the elements from both the sorted lists are compared. • The smaller of both the elements is than sorted in the third array. • The sorting s complete when all the elements from both the lists are placed in the third list.
  • 43. Merge Sort • Suppose array a & b contain 5 elements each. Than merge sort algorithm works as follows: • The arrays a & b are sorted using any algorithm • The 0th element from 1st array is compared with the 0th element in the 2nd array. The smaller of the two is placed in the 3rd array. • Now the biggest of them is compared with the 1st element of the other array. • The smaller of the two is placed in the third array. • The same procedure is repeated till end of one of the arrays is reached. • The remaining elements from the other array are placed directly into the third list as they are already in the sorted order.
  • 44. Merge Sort – Algorithm • To sort the entire sequence A[1 .. n], make the initial call to the procedure MERGE-SORT (A, 1, n). • MERGE-SORT (A, p, r) 1. IF p < r // Check for base 2. THEN q = FLOOR[(p + r)/2] // Divide step 3. MERGE (A, p, q) // Conquer step. 4. MERGE (A, q + 1, r) // Conquer step. 5. MERGE (A, p, q, r) // Conquer step.
  • 45.
  • 47. Introduction • Searching is an operation which finds the location of a given element in a list. • The search is said to be successful or unsuccessful depending on whether the element that is being searched for is found or not.
  • 48. Linear Search • This is the simplest method of searching. • In this method the element to be found is sequentially searched in the list. • This method can be applied to a sorted or an unsorted array. • Searching in case of a sorted list starts from the 0th element and continues until the element is found or an element whose value is greater than the value being searched is reached. • Searching in case of an unsorted list starts from 0th element and continues until element is found or end or list is reached
  • 49. Unsorted List – Linear Search FOR (I=0; I<N-1;I++) { IF (ARR [ I ] = = NUM) BREAK } IF (I = = 10) PRINT (NO. NOT PRESENT) ELSE PRINT (NO. PRESENT)
  • 50. Sorted List – Linear Search FOR (I=0; I<N-1;I++) { IF (ARR [9] < NUM | | ARR [I] >= NUM) { IF (ARR [I] = = NUM) PRINT (PRESENT) ELSE PRINT (ABSCENT) BREAK } }
  • 51. Binary Search – This method is very fast and efficient. – This search requires the list of elements to be in sorted order. – In this method to search for an element we compare with the element present at the centre of the list. – If it matches than the search is successful.
  • 52. Binary Search – Otherwise the list is divided into two halves: – One from the 0th element to the centre of the list. – The other from the centre to the end of the list. – As a result all the elements in the first half are smaller than the centre element whereas all elements in the second half are greater than the center element. – The searching will now precede in either of t he two halves depending on whether the element is greater or smaller than the middle element. – Same process of comparing the center element and then dividing the array is repeated for the first or second half. – This process is repeated till element is found or division results in one element
  • 53. Binary Search – Algorithm WHILE (NOT END OF INPUT) { LOW = 0 HI = N-1 WHILE (LOW<= HI) { MID = (LOW + HI) / 2 IF (KEY = = K [MID]) RETURN MID IF (KEY < K [MID]) HI = MID – 1 ELSE LOW = MID + 1 } }
  • 55. Introduction • Definition: A binary tree, T, is either empty or such that: – T has a special node called the root node; – T has two sets of nodes, LT and RT, called the left subtree and right subtree of T, respectively; – LT and RT are binary trees
  • 57. Binary Tree - Terms • Leaf: node that has no left and right children • Parent: node with at least one child node • Level of a node: number of branches on the path from root to node • Height of a binary tree: number of nodes no the longest path from root to node
  • 58. Binary Tree – Traversal • Inorder – Traverse the left subtree – Visit the node – Traverse the right subtree • Preorder – Visit the node – Traverse the left subtree – Traverse the right subtree • Postorder – Traverse the left subtree – Traverse the right subtree – Visit the node

Notas do Editor

  1. A * B - ( C + D ) + E