• Nenhum resultado encontrado

dsmaterial

N/A
N/A
Protected

Academic year: 2021

Share "dsmaterial"

Copied!
16
0
0

Texto

(1)

UNIT – V DATA STRUCTURES Introduction:

 A data may consists of several items, each data item may be stored internal in different ways is called “Data structures”.

 The internal storage representation of a data item is called its data structure.  Data structures are mainly divided into two types. They are

 Primitive Data structures  Non-Primitive Data structures Primitive Data structures:

These are the data structures which are stored directly by a system and we can perform any operations on this data items. For example, the data types int, float, char, double etc are belongs to the primitive data structures

Non-Primitive Data structures:

These are the data structures which are not stored directly by a system, they are classified into two types. They are

 Linear Data structures  Non Linear Data structures Linear Data structures:

This type of data structure involves arranging the elements in a sequential order. For example, Arrays, Linked list, Stack, Queues, etc.

Non Linear Data structures:

This type of Data structures involves arranging the elements in a Hierarchical order. For example Trees and Graphs.

BUBBLE SORT

 Bubble sort is a simplest sorting algorithm, it is also known as exchange sort.

 In bubble sort algorithm array is traversed from 0 to the length-1 index of the array and compared one element to the next element and swap values in between if the next element is less than the previous element.

 In other words, bubble sorting algorithm compare two values and put the largest value at largest index. The algorithm follow the same steps repeatedly from 0 to n-1 index until the values of array is sorted.

 In worst-case the complexity of bubble sort is O(n2) and in best-case the complexity of bubble sort is Ω(n).

 The algorithm follows the same steps iteratively unlit elements are not sorted. In our example we are taking the following array values

12 9 4 99 120 1 3 10

The basic steps followed by

algorithm:- In the first step compare first two values 12 and 9. As 12>9 then we have to swap these values the new sequence is

 In next step take next two values 12 and 4.

Compare these two values .As 12>4 then we have to swap these values. Then the new sequence will be

12 9 4 99 120 1 3 10

9 12 4 99 120 1 3 10

(2)

 We have to follow similar steps up to end of array. e.g.

When we reached at last index .Then restart same steps unlit the data is not sorted.

The output of this example will be : 1 3 4 9 10 12 99 120

Program :

import java.util.*; class Bubble

{

public static void main(String args[])throws Exception {

Scanner in=new Scanner(System.in); int a[]=new int[10];

int i,n;

System.out.println("Enter how many elements:"); n=in.nextInt();

System.out.println("Enter array elements:"); for(i=0;i<n;i++)

a[i]=in.nextInt(); bsort(a,n);

System.out.println("Aftter sorting array elements are:"); for(i=0;i<n;i++)

System.out.println(a[i]); }

public static void bsort(int a[],int x) { int i,j,t; for(i=0;i<x;i++) for(j=1;j<(x-i);j++) if(a[j]<a[j-1]) { t=a[j]; a[j]=a[j-1]; a[j-1]=t; } } } Algorithm: Step1 : Start

Step2 : Repeat i=0 to n Step3 : Repeat j=1 to (n-i) Step4 : if(a[j]<a[j-1] 4.1 : swap(a[i],a[j-1]) Step5: return Step6 : Stop SELCTION SORT

Page:2

9 4 12 99 120 1 3 10 9 4 12 99 1 120 3 10 9 4 12 99 1 3 120 10 9 4 12 99 1 3 10 120

(3)

In selection sorting algorithm, find the minimum value in the array then swap it first position. In next step leave the first value and find the minimum value within remaining values. Then swap it with the value of minimum index position. Sort the remaining values by using same steps. Selection sort is probably the most intuitive sorting algorithm to invent.

The complexity of selection sort algorithm is in worst-case, average-case, and best-case run-time of Θ(n2), assuming that comparisons can be done in constant time.

Code description:

 In selection sort algorithm to find the minimum value in the array. First assign minimum index in key (index_of_min=x). Then find the minimum value and assign the index of minimum value in key (index_of_min=y). Then swap the minimum value with the value of minimum index. At next iteration leave the value of minimum index position and sort the remaining values by following same steps.

1. Initaily variable index_of_min=0;

2.Find the minimum value in the unsorted array.

3. Assign the index of the minimum value into index_of_min variable. 4. Swap minimum value to first position.

5. Sort the remaining values of array (excluding the first value). import java.util.*;

class selection {

public static void main(String args[])throws Exception {

Scanner in=new Scanner(System.in); int a[]=new int[10];

int i,n;

System.out.println("Enter how many elements:"); n=in.nextInt();

System.out.println("Enter array elements:"); for(i=0;i<n;i++)

a[i]=in.nextInt(); ssort(a,n);

System.out.println("Aftter sorting array elements are:"); for(i=0;i<n;i++)

System.out.println(a[i]); }

public static void ssort(int a[],int x) { int i,min,loc,j,t; for(i=0;i<(x-1);i++) { min=a[i]; loc=i; for(j=i+1;j<x;j++) { if(min>a[j]) { min=a[j]; loc=j; } } t=a[i]; a[i]=a[loc]; a[loc]=t; } Algorithm:

1. Repeat for i=1 to (x-1) 2. min  a[i]

3. loc  i

4. Repeat for j=(i+1) to x 5. if(min>a[j])

5.1: min  a[j] 5.2: loc  j 6. Swap(a[i],a[loc]) 7. Return

(4)

INSERTION SORT

 Insertion sorting algorithm is similar to bubble sort. But insertion sort is more efficient than bubble sort because in insertion sort the elements comparisons are less as compare to bubble sort.

 In insertion sorting algorithm compare the value until all the prior elements are lesser than compared value is not found. This means that the all previous values are lesser than compared value.

 This algorithm is more efficient than the bubble sort .Insertion sort is a good choice for small values and for nearly-sorted values. There are more efficient algorithms such as quick sort, heap sort, or merge sort for large values.

 The complexity of insertion sorting is O(n) at best case of an already sorted array and O(n2) at worst case

Code Description .

 In insertion sorting take the element form left assign value into a variable. Then compare the value with previous values. Put value so that values must be lesser than the previous values. Then assign next value to a variable and follow the same steps relatively until the comparison not reached to end of array.

Algorithm:

1. Repeat for i=1 to n 2. j  i

3. t  a[i]

4. Repeat while(j>0 && a[j-1]>t) 4.1: a[j]  a[j-1]

4.2: j  j-1 5. a[j]  t 6. Return

(5)

Program:

import java.util.*; class insertion {

public static void main(String args[])throws Exception {

Scanner in=new Scanner(System.in); int a[]=new int[10];

int i,n;

System.out.println("Enter how many elements:"); n=in.nextInt();

System.out.println("Enter array elements:"); for(i=0;i<n;i++)

a[i]=in.nextInt(); isort(a,n);

System.out.println("Aftter sorting array elements are:"); for(i=0;i<n;i++)

System.out.println(a[i]); }

public static isort(int a[],int x) { int i,j,t; for(i=1;i<x;i++) { j=i; t=a[j]; while((j>0)&&(a[j-1]>t) { a[j]=a[j-1]; j--; } a[j]=t; } } } QUICK SORT

 It is one of the more efficient sorting algorithm, invented by Prof.C.A.R.Hoare in 1960.  This algorithm works by divided-conquer rule.

 The process for sorting the elements using quick sort is as follows. 1. Take the first element of the list as pivot.

2. Compare the pivot element one by one from right to left for smallest value than the pivot element. 3. Interchange the element with pivot element.

4. Now the comparison will start. The interchange element position from left to right for biggest value than the pivot element.

5. Interchange the element with pivot element.

6. Repeat the same process until pivot element is at its proper position. 7. Create two sublists left and right side of pivot.

(6)

For example, we take the following list of elements and process through quick sort.

5 6 3 2 4 7 9

 We are taking 5 as pivot element and we will have to start comparison from right to left for smaller element.

5 6 3 2 4 7 9

 Interchange the smaller element with pivot element. Now the comparison will start from left to right for greater element.

4 6 3 2 5 7 9

 Interchange the bigger element with pivot element. Now the comparison will start from right to left for smaller element.

4 5 3 2 6 7 9

 Interchange the smaller element with pivot element.

4 2 3 5 6 7 9

 There is no element bigger than the pivot element. So it is at its proper position in the list. So we can

divide the list into two sublists left and right side of pivot.

4 2 3 5 6 7 9

 Now, we have to continue the same process for sublists. At the end all the elements of the list will be its proper position.

LINKED LIST

 Linked list refers to a linear collection of data items, which are inserted and deleted dynamically.  Linked list is a collection of nodes. Each node contains two fields. Namely, data field and link field. Node

Data Field

 The data field contains information of the node and the link field contains address of next node or null.

 The representation of a node is as follows: class Node

{

int data; Node link; }

 The operations perform the linked list are as follows:

a) Creation of a list : This operation involves creating a linked list. b) Insertion : This operation involves to insert a node in any position. c) Deletion : This operation involves to deletes a node from any position. d) Sorting : This operation involves rearranging the data in any order.

e) Searching : This operation involves to finds the position of the node in a linked list.

f) Merging : This operation makes it possible to combine the nodes of two similar linked lists into single linked list.

g) Traversing : This operation involves accessing the nodes data through process. Types of linked lists:

There are four types of linked lists. They are 1. Single linked list.

2. Doubly linked list. 3. Circular linked list. 4. Header linked list. 1. Single linked list :

 A single linked list is also called as one way list.

 A single linked list is a collection of nodes. Each node contains two parts. The first part contains the data of the node and the second part contains address of the next node in the list.

Page:6

10 20 30 40 null

(7)

 Inserting a node at the end of the list:

To create a node the class definition is as follows: class Node

{

int data; Node link; }

Node q=new Node(); q.data=50;

q.link=null; p.link=q;

p q

 Inserting a node at the specific position of the list: To create a node the class definition is as follows:

class Node {

int data; Node link; }

Node q=new Node(); q.data=25;

q.link=p.link;

p.link=q; q

p

 Deleting a node at the end of the list:

p

The statement is p.link=null;

p

 Deleting a node at the end of the list:

p q The statement is P.link=q.link; p q 10 20 30 40 50 null 10 20 30 40 null Start 25 10 20 30 40 null Start 10 20 30 null Start 10 20 30 40 null Start 10 20 30 40 null Start

(8)

2. Doubly linked list :

 A doubly linked list can move in both directions, since each node contains two link fields.

 The representation of node is as follows: class Node

{

int data;

Node left,right; }

 The left link contains the address of the previous node and right link contains the address of the next node.

3. Circular linked list :

 In a linked list the last node link field contains the address of the first node is called a circular linked list.

 To change the linked list into the circular linked list, the statement is q.link=first;

first q

4. Header linked list :

 This type of list contains a special node called header node, it contains address of the first node and no information.

 The header node is placed at the beginning of the list. The list pointer ‘start’ is positioning to the header node.

Header node Advantages:

 Linked list provides a flexibility to arrange the items efficiently and also quick accessing of items in the list.

 Using linked lists we can allocates the memory dynamically and also releases the unused memory dynamically. This effective memory utilization is possible.

 In linked lists the data elements may be inserted (or) deleted in simple and in less time. Disadvantages:

 For fixed length list, it will be better to use an array than linked list.

 Linked list will occupy more space than an array for same number of items, because each item has an additional link field.

Page:8

null 10 20 30 40 null

10 20 30 40

10 20 30 40 null

(9)

STACKS

 A stack is linear collection of data items, which are inserted and deleted at same end. Such end is called top and other end is called bottom.

 In stack, we delete the item what we inserted at last. Such process is referred as Last-In-First-Out(LIFO).

 In stacks insertion and deletion operations are performed as PUSH and POP. These two operations are performed at the top end of the stack.

 A stack may be represented in the memory mainly in two ways. They are (1) Arrays

(2) Linked list

 For example, an array based stack with five elements will be represented as follows.

POP PUSH

top  The stack pointer ‘top’ is pointing to the top element of the stack.

 In the array representation of a stack, when the stack is empty, then the top position is ‘-1’.

 In several applications the size of the stack may modify during execution of a program. For this problem we represented stack using linked list.

 For example, following figure shows a linked list representation a stack. top 3

2

1

 In the linked list representation of a stack, when the stack is empty, then the top position is ‘0’. Stack Operations

PUSH operation: This operation inserts an element to the top of the stack. To PUSH an element, we have to check weather the stack is full or not.

a) If it is full, we display an error message “Stack Overflow”.

b) If it is not full, we increasing top by one and insert an element to the top of the stack.  The algorithm for PUSH is as follows.

1. Start

2. if top==(size-1) then 2.1: Print “Stack Overflow” 2.2: return 3. toptop+1 4. s[top]x 5. Stop. 30 20 10 30 10 null 20

(10)

POP operation: This operation deletes an element from the top of the stack. To POP an element, we have to check weather the stack is empty or not.

c) If it is empty, we display an error message “Stack Underflow”.

d) If it is not empty, we delete the top most element and then decreasing top by one.  The algorithm for POP is as follows.

1. Start

2. if (top==-1) then

2.1: Print “Stack Underflow” 2.2: return

3. xs[top] 4. toptop-1 5. Stop.

QUEUES

 A queue is linear collection of data items, which are inserted and deleted in different ends.  Insertion end is called as REAR, and deletion end is called as FRONT.

 In queue is to be process is referred as First-In-First-Out(FIFO).

 A queue may be represented in the memory mainly in two ways. They are (3) Arrays

(4) Linked list

 For example, an array based queue with five elements will be represented as follows. REAR

FRONT

 In the array representation of a queue, when the queue is empty, then the rear position is ‘-1’.

 In several applications the size of the queue may modify during execution of a program. For this problem we represented queue using linked list.

 For example, following figure shows a linked list representation a queue.

FRONT REAR

 In the linked list representation of a queue, when the queue is empty, then the rear position is ‘0’. Queue Operations

REAR operation: This operation inserts an element to the rear of the queue. To insert an element, we have to check weather the queue is full or not.

e) If it is full, we display an error message “Queue Overflow”.

f) If it is not full, we increasing rear by one and insert an element to the rear of the queue.  The algorithm for REAR is as follows.

1. Start

2. if rear==(size-1) then 2.1: Print “Queue Overflow” 2.2: return

3. rearrear+1 4. q[rear]x 5. Stop.

FRONT operation: This operation deletes an element from the front of the queue. To delete an element, we have to check weather the queue is empty or not.

g) If it is empty, we display an error message “Queue Underflow”.

Page:10

30

20 10

(11)

h) If it is not empty, we delete the first element and then increasing front by one.  The algorithm for FRONT is as follows.

1. Start

2. if (rear==-1) then

2.1: Print “Queue Underflow” 2.2: return

3. xq[front] 4. frontfront+1 5. Stop.

Types of Queues:

1) Circular Queue : In the normal queue, when the REAR pointer reaches to the end, then insertions will

not possible even its space available at front. To overcome this problem we can implement the queue as circular queue.

front rear 50

Deletion Insertion

A circular queue is a queue in which the locations are treated as circular, such that the first location follows the last location. In a linked representation circular queue the last node is pointing to the first node.

rear

front

2) Dequeue : In a queue both insertions and deletions are may done in both ends, than it is called a

Double Ended queue (Dequeue).

Insertion

Insertion

10 20 30

Deletion Deletion

There are two types of dequeues. They are  Input Restricted Dequeue

 Output Restricted Dequeue

 An Input Restricted Dequeue allows insertions at only one end but deletions on both ends.

front rear

Insertion

10 20 … … 50

Deletion Deletion

 An Output Restricted Dequeue allows deletions at only one end but insertions on both ends.

front rear

Insertion

Insertion

10 20 … … 50

Deletion

3) Priority Queue: A priority queue is a collection of elements, which are stored according to their

70 60 10 50 20

40 30

(12)

b) If the elements are same priority, then the element added first in the queue will be processed. Priority queues are implementing job-scheduling by the operating system. The jobs with higher priority are to be processed first.

TREES Trees

 A tree is a finite non empty set of elements.

 When drawing a tree each element is represented as a node and a link between the node and its subtrees is called as edge. One of these elements must be a root node.

In the above example

 A, B, C, D, E, G, H, I, J are called as nodes.  A is the root node.

 B, C, D are the subtrees of root node A.

 The number of subtrees of a node is called degree of node. Eg: Degree of A = 3

Degree of B = 2 Degree of C = 1 Degree of D = 3

 The node with degree zero will be called as leaf node or terminal node. Eg: E, F, G, H, I, J

 The node with degree greater than zero will be called as non-terminal node. Eg: A, B, C, D

 The depth or height of the tree refers to the maximum level of the tree. The height of above tree is 3.  A tree with no root node will be called as forest.

Binary Tree

A binary tree is a finite empty set of elements. When binary tree is not empty, it has a root node, and the remaining elements are partition into two binary trees, which are called as left subtree and right subtree.

The difference between binary tree and tree as follows:  A binary tree can be empty, while a tree cannot be empty.

 In a binary tree each element have exact two subtrees, but in a tree each element have any number of subtrees.  exactly (n-1) edges. Nodes = n = 7

Page:12

A B C D H G F E I J A B C F E D G A B C F E D G A B C E G

(13)

Edges = (n-1) = 6

A binary tree of height ‘h’ have exactly 2h-1 elements in it. This type of binary tree is called as full binary tree.

Height = h= 3

Elements = 2h-1 = 23-1 = 7

 If we delete ‘k’ elements from any full binary tree without decreasing the height, then it will be called as complete binary tree.

Binary Tree Representation: A binary tree can be represented in two ways. They are  Arrays

 Linked lists

Array Representation:

 This is the simplest way to represent the binary trees in memory by using arrays. The root node of binary tree is stored in first location, the left child is stored in second location and right child is stored in third location and so on.

0 1 2 3 4 5 6

 In a tree, missing elements are represented by doted lines with connecting to empty circle.  Array representation will be useful, when the number of missing elements are small. This

representation makes wasteful space many elements are missed.

Linked representation:

 In linked representation each element is represented as a node. A node contains two fields. Namely, left child and right child. If a node does not have any child its field is null.

 A class definition for creating a node is as follows: class Node

{

int data;

Node left, right; }

Consider the following example.

Page:13

A B C F E D G A B C F E D G A B C F D A B D A C G A B C E G A B C E G A B C A

(14)

GRAPHS Graph:

 A graph is a collection of nodes or vertices which are joins by edges.  A graph ‘G’ is a collection of two sets. Namely, ‘V’ and ‘E’.

G=(V,E)

Where V=Collection of vertices E=Collection of edges.

 An edge with direction is called as directed edge, an edge with no direction is called as undirected edge.

 The directed edge (i, j) is different from directed edge (j,i), but the undirected edge (i, j) and (j, i) are same.

Undirected Graph:

In a graph all the edges are undirected, it is called as undirected graph. Undirected graph has an unordered pair of vertices.

G=(V,E) V={1,2,3,4}

E={(1,2)(1,4)(1,3)(2,3)(3,4)}

Directed Graph:

In a graph all the edges are directed, it is called as directed graph (or) digraph. Directed graph has an ordered pair of vertices.

G=(V,E) V={1,2,3,4}

E={(1,2)(2,3)(3,1)(3,4)(4,1)}

Loop:

If any node contains a self edge in a graph is called as a loop.

Cyclic Graph:

A graph that has cycles is called a cyclic graph.

Path 1  2  3  1 (or) 1  3  4  1 Degree:

Page:14

1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4

(15)

In an undirected graph the number of edges connected to a node is called the degree of that node.

The degree of node, d1=3 d2=2 d3=3 d4=2

In-Degree and Out-Degree:

 In a directed graph, the number of edges coming to that node is called as In-Degree of that node.  In a directed graph, the number of edges going from that node is called as Out-Degree of that node.

In-Degree of node, d1in=2 Out-Degree of node, d1out=1

d2in=1 d2out=1

d3in=1 d3out=2

d4in=1 d4out=1

Source Node:

A node when has no incoming edges, but has out going edges is called as a source node.

Connected Graph:

If there is an edge from one node to all other nodes in an undirected graph is called as connected graph.

Strongly Connected Graph:

If there is an edge from one node to all other nodes in a directed graph is called as connected graph.

Complete Graph:

 An undirected graph with ‘n’ nodes contains n(n-1)/2 edges is called as complete graph.  In the case of directed graph with ‘n’ nodes contains n(n-1) edges is called as complete graph. Graph Representation 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4

(16)

 Adjacency matrix representation  Linked lists

Adjacency matrix:

 Adjacency matrix is a square matrix, which keeps the information of adjacent nodes.  A graph G=(V,E) for adjacent matrix A is as follows

A[i][j] = 1, if there is edge from i to j 0, if there is no edge from i to j  For undirected graph

1 2 3 4 1 0 1 1 1 A[i][j] = 2 1 0 1 0 3 1 1 0 1 4 1 0 1 0

 For directed graph

1 2 3 4 1 0 1 0 1 A[i][j] = 2 1 0 1 1 3 0 0 0 1 4 1 0 1 0 Linked Representation:

In this representation we maintain two lists. The first list will keeps all the nodes of in the graph. The second list will maintains the list adjacent nodes for each node.

 For undirected graph

 For directed graph

Page:16

1 2 3 4 1 2 3 4 1 2 3 4 4 4 N N 3 2 2 3 1 1 3 N 1 2 4 N 1 3 N 1 2 3 4 1 2 4 N 2 3 4 1 3 N 4 N 1 3 4 N

Referências

Documentos relacionados

In this context, the objectives of the present study were (a) to evaluate whether the structural complexity of an indivi- dual host (test of the structural complexity hypothesis)

It was also observed that the birds that had received vitamin D and had their estimated gait score 0 did not present leg problems, while those who received vitamin D, but had

To assess the effect of size on shape, we re- gressed the shape of the collection of specimens (cap- tured as coordinates of landmarks) onto size (CS, log transformed) as

Habitat and time of activity: Oxyrhopus melanog- enys is a moderate-sized pseudoboine (maximum SVL = 901 mm, female; this study) and the data avail- able indicate that this is

Another user-friendly program used in population ge- netics for pedigree analysis is CFC (Colleau, 2002), which can provide general information on the structure of pedi- grees,

However, the mean score of Repurchase Intentions (p&lt;.01) was significantly higher in ‘Die - hard’ than in ‘Occasional’, while no statistically significant differences

Ao nível da implementação técnica do projecto e da estabilidade da plataforma não se verificam problemas de maior por estar garantida a sua manutenção nos servidores do Centro

rendimento em xilitol e um maior rendimento de etanol [Matsushika et al., 2009]. Para além da introdução de diversas vias de conversão xilose-xilulose em S. cerevisiae,