Está en la página 1de 20

DATA STRUCTURES USING C

UNIT-IV

GRAPHS AND SORTING TECHNIQUES


1. What is a graph? Explain graph traversal in detail?

Ans: Graph is a set of nodes and edges.


G=[V,E] ,V represent nodes or vertices

V={v1, v2,……….. vn}


E represents edges or pair of nodes i.e., E=[( vi, vj)]
Graph Traversal Methods:
1. DFS Traversal or Depth first search

2. BFS Traversal or Breadth first search

DFS: It uses DS stack. The elements are traversed in depth wise.

• DFS is an uninformed search that progresses by expanding the first child node of the
search graph that appears and thus going deeper and deeper until a goal node is found, or
until it hits a node that has no children. Then the search backtracks, returning to the most
recent node it hadn't finished exploring. In a non-recursive implementation, all freshly
expanded nodes are added to a LIFO stack for exploration.

Algorithm:
1. Start
2. Initialize all the nodes to the ready state.
3. Begin with any node which is in the ready state and push into the stack and change its
status to the waiting state.
4. Repeat the steps 5 and 6 until stack is empty and no nodes are in the ready state.
5. Pop the top node say 'k' of the stack and print it, change its status to the processed state.
6. Push all the adjacent nodes of 'k' which are still in the ready state and change their status
to the waiting state.
7. Stop
BFS Traversal or Breadth first search
• BFS is an uninformed search method that aims to expand and examine all nodes of a
graph or combinations of sequence by systematically searching through every solution. In
other words, it exhaustively searches the entire graph or sequence without considering the
goal until it finds it.

Algorithm:

1. Start
2. Initialize all the nodes to the ready state.
3. Begin with any node which is in the ready state and insert into the queue, change the
status of the node to the waiting state.
4. Repeat the steps 5 and 6 until queue is empty and no nodes are in the ready state.
5. Remove the front node of queue and print it, change its status to the processed state.
6. Insert all the adjacent nodes of the printed element to the rear of the queue, which are
still in the ready state and change their status to the waiting state.
7. Stop

2. Explain about DFS with example?

Ans:DFS: It uses DS stack. The elements are traversed in depth wise.


DFS is an uninformed search that progresses by expanding the first child node of
the search graph that appears and thus going deeper and deeper until a goal node is found,
or until it hits a node that has no children. Then the search backtracks, returning to the most
recent node it hadn't finished exploring. In a non-recursive implementation, all freshly
expanded nodes are added to a LIFO stack for exploration.
Mark S as visited and put it onto the stack. Explore any unvisited adjacent node from S. We
have three nodes and we can pick any of them. For this example, we shall take the node in
an alphabetical order

Mark A as visited and put it onto the stack. Explore any unvisited adjacent node from A.
Both S and D are adjacent to A but we are concerned for unvisited nodes only.
Visit D and mark it as visited and put onto the stack. Here, we have B and C nodes, which
are adjacent to D and both are unvisited. However, we shall again choose in an alphabetical
order.

We choose B, mark it as visited and put onto the stack. Here B does not have any unvisited
adjacent node. So, we pop B from the stack

We check the stack top for return to the previous node and check if it has any unvisited
nodes. Here, we find D to be on the top of the stack.
Only unvisited adjacent node is from D is C now. So we visit C, mark it as visited and put
it onto the stack.

3. Write a c program to implement BFS

#include<stdio.h>
int a[20][20],q[20],visited[20],n,i,j,f=0,r=-1;
Void bfs(int v)
{
for(i=1;i<=n;i++)

if(a[v][i] && !visited[i])


q[++r]=i;
if(f<=r)
{
visited[q[f]]=1;

bfs(q[f++]);
}
}
void main()
{
int v;
printf("\n Enter the number of vertices:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
q[i]=0;
visited[i]=0;
}
printf("\n Enter graph data in matrix form:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);

printf("\n Enter the starting vertex:");


scanf("%d",&v);
bfs(v);
printf("\n The node which are reachable are:\n");
for(i=1;i<=n;i++)
if(visited[i])
printf("%d\t",i);

else
printf("\n Bfs is not possible");

}
4. Write a c program to implement DFS

#include<stdio.h>
int a[20][20],reach[20],n;
void dfs(int v)
{
int i;
reach[v]=1;
for(i=1;i<=n;i++)
if(a[v][i] && !reach[i])
{
printf("\n %d->%d",v,i);
dfs(i);
}
}
void main()
{
int i,j,count=0;

printf("\n Enter number of vertices:");


scanf("%d",&n);
for(i=1;i<=n;i++)
{
reach[i]=0;
for(j=1;j<=n;j++)
a[i][j]=0;
}
printf("\n Enter the adjacency matrix:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
dfs(1);
printf("\n");
for(i=1;i<=n;i++)
{
if(reach[i])
count++;
}
if(count==n)
printf("\n Graph is connected");
else
printf("\n Graph is not connected");

}
Sorting

5. Explain about Insertion Sort in detail with example? Implement Insertion Sort and
analyze.

Ans: The insertion sort inserts each element in proper place. This is same as playing cards,
in which we place the cards in proper order. There are n elements in the array and we place
each element of array at proper place in the previously sorted element list.

Let us take there are n elements the array arr. Then process of inserting each element in
proper place is as-

Pass 1- arr[0] is already sorted because of only one element.

Pass 2-arr[1] is inserted before or after arr[0].

So arr[0] and arr[1] are sorted.

Pass 3- arr[2] is inserted before arr[0] or in between arr[0] and arr[1] or after arr[1].

So arr[0], arr[1] and arr[2] are sorted

Pass 4- arr[3] is inserted into its proper place in array arr[0], arr[1], arr[2]

So, arr[0] arr[1] arr[2] and arr[3] are sorted.

……………………………………….

…………………………………………

………………………………………..

Pass N- arr[n-1] is inserted into its proper place in array.

arr[0], arr[1], arr[2],………………………… arr[n-2].

So, arr[0] arr[1],……………………….. arr[n-1] are sorted.

Example:

Sort below elements in increasing order using insertion sort:

5 2 1 3 6 4

Compare first and second elements i.e., 5 and 2, arrange in increasing order.

2 5 1 3 6 4

Next, sort the first three elements in increasing order.

1 2 5 3 6 4

Next, sort the first four elements in increasing order.

1 2 3 5 6 4
Next, sort the first five elements in increasing order.

1 2 3 5 6 4

Next, sort the first six elements in increasing order.

1 2 3 4 5 6

Analysis:

In insertion sort, we insert the element before or after and we start comparison from the first
element. Since first element has no other elements before it, so it does not require any
comparison. Second element required 1 comparison, third requires 2 comparisons, fourth
requires 3 comparisons and so on. The last element requires n-1 comparisons. So, the total
number of comparisons will be-

1+2+3+………………+(n-2)+(n-1)

It’s a form of arithmetic progression series, so the sum is n/2*[(2*a)+(n-1)*d]=(n-


1)/2(2*(1))+((n-1-1)*1)=((n*(n-1))/2

Which is of O(n2)
It’s a worst case behavior of insertion sort where all the elements are in reverse order.

The advantage of insertion sort is its simplicity and it is very efficient when number of
elements to be sorted are very less. Because for smaller file size n the difference between
O(n2) and O(nlogn) is very less and O(n logn) has complex sorting technique.

Insertion sort behaves as of O(n) when elements are in sorted order and also has worth
when list of elements are near about sorted.

Algorithm:

Insertion(int x[ ],int n)

1. Start
2. set i=1
3. repeat the steps 4,5,8 and 9 while(i<n)
4. set key=x[i] and j=i-1
5. repeat the steps 6 and 7 while j>=0 && x[j]>key
6. set x[j+1] =x[j]
7. j=j-1
8. set x[j+1]=key
9. set i=i+1
10. stop
//program to arrange the given list of elements in increasing order using insertion sort
technique
#include<stdio.h>
#include<conio.h
> void main()
{
void insert(int x[],int n);
int a[10],n,i;
printf("enter n");
scanf("%d",&n);
printf("enter %d
elements",n); for(i=0;i<n;i++)
scanf("%d",&a[i]); printf("\n
before sorting:\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
insert(a,n);
printf("\n after
sorting:\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
void insert(int x[],int n)
{
int i,j,key;
for(i=1;i<n;i++)
{
key=x[i]; for(j=i-
1;j>=0&&x[j]>key;j--)
x[j+1]=x[j];
x[j+1]=key;
}
}

6. Explain about Selection Sort in detail with example? Implement Selection Sort and
analyze.
Ans:
As the name suggests selection sort is the selection of an element and keeping it in sorted
order. If we have a list of elements in unsorted order and we want to make a list of elements
in sorted order then first we will take the smallest element and keep in the new list, after that
second smallest element and so on until the largest element of list.
Let us take an array a[0],a[1],…………a[n-1] of elements. First we will search the position of
the smallest element form a[0]……….a[n-1]. Then we will interchange that smallest element
with a[0]. Now we will search position of smallest element(second smallest element because
a[0] is the first smallest element) from a[1]……..a[n-1],then interchange that smallest
element with a[1]. Similarly the process will be for a[2]……………a[n-1].
Example:

1 2 3 4 5 6 7 8 9 10
87---Unsorted
42 23 74 11 65 58 94 36 99 list
Find the minimum element and if it is not the first element, then interchange first element
and the minimum element. Then the list become
11 23 74 42 65 58 94 36 99 87---pass 1

Find the second minimum element and if it is not the second element, then interchange
second element and the second minimum element. Then the list becomes
87---pass
11 23 74 42 65 58 94 36 99 2
Continue till pass 9
87---pass
11 23 36 42 65 58 94 74 99 3
94---pass
11 23 36 42 65 58 94 74 99 4
87---pass
11 23 36 42 58 65 94 74 99 5
87---pass
11 23 36 42 58 65 94 74 99 6
87---pass
11 23 36 42 58 65 74 94 99 7
94---pass
11 23 36 42 58 65 74 87 99 8
99---pass
11 23 36 42 58 65 74 87 94 9

Analysis:
As we have seen, selection sort algorithm will search the smallest element in the array and
then that element will be at proper position. So, in pass 1 it will compare n-1 elements Same
process will be for pass 2 but this time comparisons will be n-2 because first element is
already at proper position. The elements, which are already at correct position, will not be
disturbed. Same thing we will do for other passes. We can easily write function for
comparisons as-

This is arithmetic series in decreasing order,


so Sum=(n-1)+(n-2)+(n-
3)+……………….+3+2+1 Sum=(n*(n-1))/2
Since, selection sort doesn’t see the order of elements, so its behavior is near about same for
worst and best case. The best thing with selection sort is that in every pass one element will
be at correct position, very less temporary variables will be required for interchanging the
elements and it is simple to implement.

Algorithm:
Selection(int x[ ],int n)
1. start
2. set i=0
3. repeat steps 4,5 and 7 while(i<n-1)
4. set min=i and set j=i+1
5. repeat the steps 6 while(j<n)
6. if(x[j]<x[min]) set min=j
7. temp=x[i]
x[i]=x[min]
x[min]=temp
8. stop
//program to arrange the given list of elements in increasing order using
selection sort technique
#include<stdio.h>
#include<conio.h
> void main()
{
void selection(int x[],int
n); int a[10],n,i;
printf("enter
n");
scanf("%d",&n)
;
printf("enter %d
elements",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n before
sorting:\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
selection(a,n);
printf("\n after
sorting:\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
void selection(int x[],int n)
{
int i,j,temp,min;
for(i=0;i<n-
1;i++)
{
min=i;
for(j=i+1;j<n;j++)
{
if(x[j]<x[min])
min=j;
}
temp=x[i];
x[i]=x[min];
x[min]=temp;
}
}
7. Explain about Bubble Sort in detail with example? Implement Bubble Sort and
analyze.
Ans:
If n elements are given in memory then ofr sorting we do following steps:
1. First compare the 1st and 2nd element of array if 1st <2nd then compare the 2nd with 3rd.
2. If 2nd >3rd
Then interchange the value of 2nd and 3rd.
3. Now compare the value of 3 (which has the value of 2nd) with 4th.
rd

4. Similarly compare until the (n-1)th element is compared with nth element.
5. Now the highest value element is reached at the nth place.
6. Now elements will be compared until n-1 elements.

Example:

42 23 74 11 65 58 94 36 99 87
99—
23 42 11 65 58 74 36 94 87 pass1
99—
23 11 42 58 65 36 74 87 94 pass2
99—
11 23 42 58 36 65 74 87 94 pass3
99—
11 23 42 36 58 65 74 87 94 pass4
99—
11 23 36 42 58 65 74 87 94 pass5
99—
11 23 36 42 58 65 74 87 94 pass6
99—
11 23 36 42 58 65 74 87 94 pass7
99—
11 23 36 42 58 65 74 87 94 pass8
99—
11 23 36 42 58 65 74 87 94 pass9

Algorithm

Bubblesort(int x[ ],int n)
1. start
2. set i=0
3. repeat steps 4,5 and 8 while(i<n-1)
4. j=0
5. repeat steps 6,7 while(j<n-i-1)
6. if x[j]>x[j+1]
//exchange x[i] and
temp=x[j] x[j]
x[j]=x[j+1]
x[j+1]=temp
7. set j=j+1
8. set i=i+1
9. stop
Analysis:
In bubble sort, n-1 comparisons will be in 1st pass, n-2 in 2nd pass, n-3 in 3rd pass and so on,
So, its very simple to calculate the number of comparisons. Total number of comparisons will
be-
(n-1)+(n-2)+(n-3)+…………………+3+2+1

It’s a form of arithmetic progression series. So, the sum is (n*(n-


1))/2. Which is O(n2)
The main advantage is simplicity of algorithm, additional space requirement is only
one temporary variable and it behaves as O(n) for sorted array of elements.
Worst case performance=0.5*n*(n-1)=O(n2)
Average case performance=O(n2)
Disadvantage of bubble sort:
It is acceptable for sorting a table which contains a small number of records, but it becomes
difficult for large sized tables.

//program to arrange the given list of elements in increasing order using bubble sort
technique
#include<stdio.h>
void main()
{
void bubble(int x[],int n);
int a[10],n,i; printf("enter
n"); scanf("%d",&n);

printf("enter %d
elements",n); for(i=0;i<n;i++)
scanf("%d",&a[i]); printf("\n
before sorting:\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
bubble(a,n);
printf("\n after
sorting:\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
void bubble(int x[],int n)
{
int i,j,temp;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
if(x[j]>x[j+1]
)
{
temp=x[j];
x[j]=x[j+1];
x[j+1]=temp;
}
}
}
8. Explain about Quick Sort in detail with example? Implement Quick Sort and
analyze.
Ans:
The idea behind this sorting is that sorting is much easier in two short lists rather than one
long list. Divide and conquer means divide the big problem into two small problems and then
those two small problems into two small ones and so on. As example, we hve a list of 100
names and we want to list them alphabetically then we will make two lists for names. A-L
and M-Z from original list. Then we will divide list A-L into A-F and G-L and so on until the
list could be easily sorted. Similar policy we will adopt for the list M-Z.

In quick sort we divide the original list into two sublists. We choose the item from list called
key or pivot form which all the left side of elements are smaller and all the right side of
elements are greater than that element. So we can create two lists, on list is on the lsft side of
pivot and second list is on right side of pivot, means pivot will be in its actual position. Hence
there are two conditions for choosing pivot-
1. All the elements on the left side of pivot should be smaller or equal to the pivot
2. All the elements on the right side of pivot should be greater than or equal to
pivot.Similarly we choose the pivot for dividing the sublists until there are 2 or more
elements in the sublist.
The process for sorting the elements through quick sort is as-
1. Take the first element of list as pivot.
2. Place pivot at the proper place in list. So one element of the list i.e., pivot will be at its
proper place.
3. Create two sublists left and right side of pivot.
4. Repeat the same process until all elements of list are at proper position in list.
For placing the pivot at proper place we have a need to do the following process-
1. Compare the pivot element one by one from right to left for getting the element which
has value less than pivot element.
2. Interchange the element with pivot element.
3. Now the comparison will start from the interchanged element position form left to
right for getting the element which has higher value than pivot.
4. Repeat the same process until pivot is at its proper position.

Example:

48 29 8 59 72 88 42 65 95 19 82 68
Pivot

19 29 8 59 72 88 42 65 95 48 82 68
Pivot
19 29 8 48 72 88 42 65 95 59 82 68
Pivot
19 29 8 42 72 88 48 65 95 59 82 68
Pivot

19 29 8 42 48 88 72 65 95 59 82 68
Pivot

[19 29 8 42] 48 [88 72 65 95 59 82 68]


Sublist sublist
1 2

[8 29 19 42] 48 [68 72 65 95 59 82 88]


Pivot
Pivot

[8 19 29 42] 48 [68 72 65 88 59 82 95]


Pivot Pivot

[95
[8 19 29 42] 48 [68 72 65 82 59] 88 ]
Pivot

8 19 29 42 48 [59 72 65 82 68] 88 95
Pivot
8 19 29 42 48 [59 68 65 82 72] 88 95
Pivot
8 19 29 42 48 [59 65] 68 [82 72] 88 95
Pivot
8 19 29 42 48 [59 65] 68 72 82 88 95

Analysis:

Time requirement of quick sort depends on the position of pivot in the list, how pivot is
dividing list into sub lists. It may be equal division of list or may be it will not divide also.

Average Case: In average case we assume that list is equally divided means list1 is equally
divided in to two sub lists, these two sub lists into four sub lists and so on.
If there are n elements in the list, where n is approximately 2m. Hence we can say m=log2n.

In the list of n elements, pivot is placed in the middle with n comparisons and the left and
right subtrees have approximately n/2 elements each. Hence these require again n/2
comparisons each to place their pivots in the middle of the lists. These two lists are again
divided into 4 sublists and so on.

Total number of comparisons=n+2*n/2+4*n/4+8*n/8+……………….n*n/n

=n+n+n+………….+n(m times)

=O(n*m)
=O(nlog2n )
The number of comparison at any level will be maximum n. So we can say run time of quick
sort will be of O(nlogn)

Worst Case: Suppose list of elements are already in sorted order. When we find the pivot then
it will be first element. So here it produces only 1 sub list which is on right side of first
element second element. Similarly other sub lists will be created only at right side. The
number of comparison for first element is n, second element requires n-1 comparisons and so
on. So the total number of comparisons will be

=n+(n-1)+(n-2)+…………+3+2+1

=n(n-1)/2

Which is O(n2)
Worst case =O(n2)
Average case=Best Case=O(nlog2n)

//program to arrange the given list of elements in increasing order using quick sort
technique
#include<stdio.h>
#include<conio.h>
void main()
{
void quicksort(int x[],int left,int right);
int a[10],n,i;
printf("enter n");
scanf("%d",&n);
printf("enter %d elements",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n before sorting:\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
quicksort(a,0,n-1);
printf("\n after sorting:\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}

void quicksort(int a[],int left,int right)


{
int l=left,r=right,t;
int pivot=left;
while(left<right)
{
while(a[pivot]<=a[right]&&left<right)
right--;
if(left!=right)
{
t=a[pivot];
a[pivot]=a[right];
a[right]=t;
pivot=right;
}
while(a[pivot]>=a[left]&&left<right)
left++;
if(left!=right) {
t=a[pivot];
a[pivot]=a[left];
a[left]=t;
pivot=left;
}
}
left=l;right=r;
if(l<pivot) quicksort(a,left,pivot-
1);
if(r>pivot)
quicksort(a,pivot+1,right);
}

9. Explain about Merge Sort in detail with example? Implement Merge Sort and
analyze.
Ans:
If there are two sorted lists of array then process of combining these sorted lists into sorted
order is called merging.
Take one element of each array, compare them and then take the smaller one in third array.
Repeat this process until the elements of any array are finished. Then take the remaining
elements of unfinished array in third array.

Example:

Sorted
List1 Sorted List2 List3
1 13 24 26 2 15 27 38

1 13 24 26 2 15 27 38 1

1 13 24 26 2 15 27 38 1 2

1 13 24 26 2 15 27 38 1 2 13
13
1 13 24 26 2 15 27 38 1 2 15
13
1 13 24 26 2 15 27 38 1 2 15 24
13
1 13 24 26 2 15 27 38 1 2 15 24 26
2 13 15 24 26
1 13 24 26 2 15 27 38 1 27
After Merge sort list3 is 1 2 13 15 24 26 27 38
//Program to implement merge sort
#include<stdio.h>
#include<conio.h> void main()
{
void bubblesort(int x[],int n);
void mergesort(int a[],int b[],int c[],int n1,int n2,int n3); int a[10],b[10],c[10],n1,n2,n3,i;
printf("enter n1 and n2"); scanf("%d%d",&n1,&n2); n3=n1+n2;
printf("enter %d elements",n1); for(i=0;i<n1;i++) scanf("%d",&a[i]);
printf("enter %d elements",n2); for(i=0;i<n2;i++)
scanf("%d",&b[i]); bubblesort(a,n1); bubblesort(b,n2);
mergesort(a,b,c,n1,n2,n3);
printf("\n after sorting the elements of the c array"); for(i=0;i<n3;i++)
printf("\n %d",c[i]);
}
void bubblesort(int x[],int n)
{
int i,j,temp; for(i=0;i<n;i++)
{
for(j=0;j<n-1;j++)
{
if(x[j+1]<x[j])
{
temp=x[j];
x[j]=x[j+1];
x[j+1]=temp;}}}}
void mergesort(int a[],int b[],int c[],int n1,int n2,int n3)
{
int asize,bsize;
int apoint,bpoint,cpoint; asize=n1-1; bsize=n2-1;

apoint=0;bpoint=0;
if(n3!=n1+n2)
printf("array bounds exception");
for(cpoint=0;((apoint<=asize)&&(bpoint<=bsize));cpoint+
+)
{
if(a[apoint]<b[bpoint])
c[cpoint]=a[apoint++
]; else
c[cpoint]=b[bpoint++
];
}
while(apoint<=asize)
c[cpoint++]=a[apoint++];
while(bpoint<=bsize)
c[cpoint++]=b[bpoint++];
}
Analysis of merge sort:
Let us take an array of size n is used for merge sort. Because here we take elements in pair
and merge with another pair after sorting. So, merge sort requires maximum log2n passes.
Hence we can say merge sort requires n*log2n comparisons which is O(nlog2n).
The main disadvantage of merge sort is space requirement. It requires extra space of O (n).
10. Compare five sorting techniques?

Ans:
Sorting Best Case Average Case Worst Case Comparison
With other

sorts

Insertion O(n) O(n2) O(n2) Requires


more
comparisons
than Quick
sort but easy

Selection O(n2) O(n2) O(n2) Requires


more
comparisons
than Quick
sort but easy

Bubble O(n) O(n2) O(n2) Easy but


requires
more
comparisons

Quick O(nlogn) O(nlogn) O(n2) Fast but


difficult to
implement

Merge O(nlogn) O(nlogn) O(nlogn) ---

Heap O(nlogn) O(nlogn) O(nlogn) ---

Linear Search O(1) O(n) O(n) Number of


comparisons
are more to
search an
element.
Binary Search O(1) O(logn) O(logn) Lists are to
be in sorted
order and
number of
comparisons
are less.

También podría gustarte