Unit I: Structures and Unions (Co1) : Syntax For The Declaration of A Structure
Unit I: Structures and Unions (Co1) : Syntax For The Declaration of A Structure
Structure is a collection of data items of different data types under a common name.
Structure is a group of items in which every item is identified by its own name. These
items are the members of that structure.
struct structure_name
{
data_type member1;
date_type member2;
.
.
data_typememberN;
};
Example:
struct abc
{
char first [10];
char last[20];
}Sname, Ename; (Structure variables)
is equivalent to
struct abc
{
char first [10];
char last[20];
};
struct abcSname, Ename;
This declaration creates two structure variables. Sname and Ename each of which
contains two members: first,last.
Using Typedef to declare structure variables
Using the keyword typedef we can define any type to the easiest name that we want to
use.
Eg. : typedef struct abc node; // this defines struct abc as node
Another alternative usage of typedef is in the definition of the data type directly.
Eg. :
typedef struct student
{
char first[10];
char last[20];
} stu_type;
struct adr
{
char addr[40];
char city[10];
char state[3];
char zip[6];
};
struct student
{
char first[10];
char last[20];
};
struct newaddr
{
struct student name;
struct adr address;
};
struct book
{ char title[20];
char Author[15];
int pages;
float price;
};
Note : In above structure definition book1.price (etc.) can be treated like any other
ordinary variable.
struct book
{ char title[20];
char Author[15];
int pages;
float price;
}book1;
strcpy(book1.title, "CDS");
strcpy(book1.author,"K. Nagi Reddy");
book1.pages = 861;
book1.price= 215.00;
scanf ("%s%s%d%f",book1.title,book1.author,&book1.pages,&book1.price);
Note: The structure variables cannot be used as the normal variables in all operations such as
in relational statements, logical statements, etc.
Array Of Structures
The structure variables can be defined as an array if they required more in number.
Eg. struct marks
{
int sub1;
int sub2;
int sub3;
};
Example:
void main()
{
void display(char[],char[],int); // Function Prototype
struct book
{
char name[25], author[25];
int pages;
};
static struct book b1={"DSTC","G. SORENSON”,861};
display(b1.name,b1.author,b1.pages); // Function Call
}
struct book
{
char name[25], author[25];
int pages;
};
void main()
{
void display(struct book);
static struct book b1={"DSTC","G. SORENSON”,861};
display(b1);
}
Pointers to Structures
Example:
void main()
{
struct book
{
char name[25],author[25];
int pages;
};
struct book b1={"DSTC","TENEN",672};
struct book *ptr; /* (remember now ptr is not a variable, it is pointer) */
ptr=&b1;
printf("%s%s%d\n",b1.name,b1.author,b1.pages);
printf("%s%s%d\n",ptr->name,ptr->author,ptr->pages);
}
An illustrated example on Structures
What data type are allowed to structure members? Anything goes: basic types, arrays,
strings, pointers, even other structures. You can even make an array of structures.
Consider the program on the next few pages which uses an array of structures to make a
deck of cards and deal out a poker hand.
#include <stdio.h>
struct playing_card
{
int pips;
char *suit;
} deck[52];
void make_deck(void);
void show_card(int n);
void main()
{
make_deck();
show_card(5);
show_card(37);
show_card(26);
show_card(51);
show_card(19);
}
void make_deck(void)
{
int k;
for(k=0; k<52; ++k)
{
if (k>=0 && k<13)
{
deck[k].suit="Hearts";
deck[k].pips=k%13+2;
}
if (k>=13 && k<26)
{
deck[k].suit="Diamonds";
deck[k].pips=k%13+2;
}
if (k>=26 && k<39)
{
deck[k].suit="Spades";
deck[k].pips=k%13+2;
}
if (k>=39 && k<52)
{
deck[k].suit="Clubs";
deck[k].pips=k%13+2;
}
}
}
void show_card(int n)
{
switch(deck[n].pips)
{
case 11:
printf("%c of %s\n",'J',deck[n].suit);
break;
case 12:
printf("%c of %s\n",'Q',deck[n].suit);
break;
case 13:
printf("%c of %s\n",'K',deck[n].suit);
break;
case 14:
printf("%c of %s\n",'A',deck[n].suit);
break;
default:
printf("%c of %s\n",deck[n].pips,deck[n].suit);
break;
}
}
Output
7 of Hearts
K of Spades
2 of Spades
A of Clubs
8 of Diamonds
Unions
Unions are C variables whose syntax looks similar to structures, but act in a completely
different manner. A union is a variable that can take on different data types in different
situations. The union syntax is:
union tag_name{
type1 member1;
type2 member2;
…
};
For example, the following code declares a union data type called intfloatand a union
variable called proteus:
union intfloat {
float f;
int i;
};
union intfloat proteus;
In the example:
union item
{
int m;
float x;
char c;
}code;
** The size of a union data type will be the size of the bigger member variable.
Unions Example
The following code illustrates the chameleon-like nature of the union variable proteus
defined earlier.
#include <stdio.h>
void main() {
union intfloat {
float f;
int i;
} proteus;
proteus.i=4444 /* Statement 1 */
printf(“i:%12d f:%16.10e\n”,proteus.i,proteus.f);
proteus.f=4444.0; /* Statement 2 */
printf(“i:%12d f:%16.10e\n”,proteus.i,proteus.f);
}
Output
i: 4444 f:6.2273703755e-42
i: 1166792216 f:4.440000000e+03
• After Statement 1, data stored in proteus is an integer the the float member is full of junk.
• After Statement 2, the data stored in proteus is a float, and the integer value is
meaningless.
Structures Unions
This is the combination of different types of This is also the combination of different
variables types of variables
The Keyword used is ‘struct’ The keyword used is ‘union’
The size of a structure is the sum of the sizes The size of the union is the size of its biggest
of its individual elements element.
At any point of time all the members are At any point of time only one member is
valid valid
UnitII: FILES(co2)
The concept of files is to store data on the disk. A file is a place on the disk where
group of related data is stored. C language has number of functions to perform file operations
like,
1. Creating a file
2. Opening a file
3. Reading data from a file
4. Writing data into a file
5. Closing a file
FILE *fp;
fp=fopen(“filename”,”mode”);
fopen() is a library function which opens a file given in filename argument in the given
mode.
filename in function fopen() is a string of characters that make up a valid file for the
operating system. It contains two parts, a primary name and an extension name. The
extension name is optional.
Example: Abc.dat
Output
First.c
Transaction.txt
After all the operations are completed, a file must be closed. This can be as follows
flose(fp);
where fp is a file pointer.
The file pointer moves by one character position for every operations of getc() or
putc(). The getc() will return an end-of-file marker EOF, when end of the file has been
reached.
It is possible that an error may occur during I/O operations on a file. Typical error situations
include:
/*The following program reads a text file and counts how many times each letter from
'A' to 'Z' occurs and displays the results.*/
#include <stdio.h>
#include <stdlib>
#include <ctype.h>
int count[26];
fclose(fp);
}
/*This program uses command line arguments to read and display the contents of a file
supplied as an argument. */
#include <stdio.h>
#define CLEARS 12 /* constant */
putchar(CLEARS);
while ( --argc> 0 )
if ((fp=fopen(argv[1], "r"))==NULL)
{
printf("I can't open %s\n", argv[1]);
break;
}
else
{
while ((c= getc(fp)) !=EOF)
putc(c,stdout); /* display to the screen */
fclose(fp);
}
}
DATA STRUCTURES Unit-III (co4)
Data structures are to organize the related data to enable us to work efficiently with
data, exploring the relationships within the data. For example: stacks, lists and queues are
data structures.
Data structure is a study of different methods of organizing the data and possible
operations on these structures.
Two such fundamental data structures are arrays and structures. But these generally will
be used in association with static memory allocation(will be discussed later). These are not
convenient to use with Dynamic memory allocation.
malloc:Allocates required memory size in bytes and returns the address of the first byte of
the allocated space.
calloc: Allocates contiguous space, initializes the elements to zero and then returns a pointer
to the memory.
free: Frees previously allocated space for the pointer passed as argument.
node
Information Address
Using dynamic memory allocation Nodes can be created or deleted at any point of time.
Nodes can be inserted or deleted at any position of the list.
HEADER will contain address of the first node.
Address field of the last node contains NULL.
Declaration of a Node
Declaration:
struct node
{
int item;
struct node * link;
};
1. Initialization.
2. Insertion.
3. Deletion
4. Traversal or Display.
5. Find
6. Is empty. (Is full operation will not exist).
INSERTION: This can be done at the beginning or after position pos or at the end.
Insertion at begin:
Head
Original list
Item* Item* Item* \0
2 Item
1
Item*
New node
1. Place the address of the first node of the original list(Head) in the new node link
field.
2. Update the Head with New node address, by making it the starting node.
Insertion after position pos (This method is applicable for the ‘Insertion at last’ also):
Head
pos, temp
Item* Item* Item
2
Item* 1
new
If you want to insert after node pos, then traverse to pos node
Let temp pointing to node pos, new is the new node.
If pos = 0
Insert at begin
Else if ( pos<=no of nodes )
new->link=temp->link(operation 1 shown in fig)
temp->link=new(operation 2 shown in fig)
Else
Not possible to insert after pos
Insertion at last:
To insert a node at the end of the linked list, position temp at the last node and do the
following operations.
new->link=NULL
temp->link=new
Deletion at Begin:
Node_tobe_deleted
To delete the first node, make the Head points to the second node by using
Head = Head->link (As indicated by 1 in the figure above)
If there is only one node then head will contain NULL after deletion.
Head
Item* Item* Item
Delete from a position pos:
Head
1
temp,pos-1 pos
Item* Item* Item* Item
Node to be deleted
Process:
If pos=1
Delete at begin
Else if pos< no of nodes
1.Traverse to the node pos-1 and make temp pointing to position pos-1.
2.temp->link = temp->link->link ( As shown in operation 1 in fig. )
Else
Not possible – that node does not exist
1.Traverse to the last but one node and point temp to that node.
2.Now make temp->link = NULL.
DOUBLY LINKED LISTS: In this every node will consist two address fields, one pointing
to the next node and the other pointing to the previous. This allows us to traverse in both the
directions.
Node Declaration:
struct dnode
{
int info;
struct dnode *pre, *next;
};
If there is only one node, it’s pre and next will be NULL.
If there is more than one node, then first node pre will be NULL and the last node next will
be NULL.
INSERTION
Before Insertion
First Node Last Node
temp
To Insert Nodee at 3rd Position:
Four changes will be made while inserting a node in the middle of the list.
new->next=temp->next
new->pre=temp
temp->next->pre=new
temp->next=new
DELETION
temp
Info Info Info Info
/
First Node Last Node
Node to be deleted
The circular list has no beginning and no end. The last node points back to the first node.
Head
Item* Item* Item* Item
Insertion and deletion : While inserting at first position take care that you update your last
node’s address. After insertion, the list should be in the following manner
Head
Item* Item* Item
Before insertion
Head
Item Item Item
New Node
Item
After Insertion
To insert in middle position, the same method used in singly linked lists is followed.
Head
ite ite ite
m m m
Before insertion
Head
ite ite ite
m m m
New Node
After insertion ite
m
Delete front : Take care in updating the last node link field.
Head
Head
ite ite ite ite ite
m m m m m
Head
Head
ite ite ite ite ite
m m m m m
Generally in STACK
The insertion operation is referred to as push
The deletion operation is referred to as pop.
The stacks are referred to as a LIFO (Last In First Out ) list or FILO(First In Last Out)
list.
One end of the stack is designated as the stack-top. New items may be pushed onto the
top of the stack(in which case top of the stack moves upward to correspond to the new top
element) OR an item may be popped from top of the stack(in which case top of the stack
moves downward to correspond to the new top element).
Top ->|__B__|
|__A__|
After an element C pushed on to the Stack
Top ->|__C__|
|__B__|
|__A__|
APPLICATIONS OF STACKS
EXPRESSIONS
'PRE','POST','IN' refer to the relative position of operator with respect to the two
operands.
In PREFIX notation the operator precedes the two operands.
In POSTFIX notation the operator follows the two operands.
In INFIX notation the operator is in between the two operands.
The rule during conversion process is that operations with highest precedence are
converted first. To overcome the precedence, if () is used, then the part of expression inside ()
is to be converted first.
Examples:
Note: that the prefix form of a complex expression is not the mirror image of the post-fix
form.
[ End of If structure ]
[ End of Step 2 loop.]
7. Exit.
Example: ((A-(B+C))*D)$(E+F)
SYMBOL POSTFIX STRING OPSTACK
( (
( ((
A A ((
- A ((-
( A ((-(
B AB ((-(
+ AB ((-(+
C ABC ((-(+
) ABC+ pop ((-
) ABC+ pop (
* ABC+- (*
D ABC+-D (*
) ABC+-D* pop (
$ ABC+-D* $
( ABC+-D* $(
E ABC+-D*E $(
+ ABC+-D*E $(+
F ABC+-D*EF $(+
) ABC+-D*EF+ $
ABC+-D*EF+$ pop empty
Evaluation of a Postfix expression: 6 2 3 + - 3 8 2 / + * 2 $ 3 + result is 52
Types of queues
Circular queue
Priority queue
Dequeue
Applications of Queues:
Operations on a Queue:
PRIORITY QUEUE
The priority queue is a data structure in which the internal organization of the
elements determine the result of its basic operations ENQUEUE and DEQUEUE.
Ascending Priority Queue: This Queue is a collection of items into which items can be
inserted arbitarily and from which the smallest item can be removed directly.
Descending Priority Queue: This is similar but the biggest item can be deleted directly.
DEQUEUE
A deque is an ordered set of items from which items may be deleted at either end and into
which items may be inserted at either end. There are insert begin, insert end, delete begin,
delete end oprerations.
1. The input restricted dequeue allows insertions at only one end
2. The output restricted dequeue permits deletions from one end only
Front Rear
Insertio Deletio
n nn
Deletio Insertio
nn n
TREES
A tree is a finite set of one or more elements such that there is a specially designated
node called the root. The remaining nodes are partitioned into n > = 0 disjoint sets T1……Tn
where each of these sets is a tree T 1……Tn are called the subtrees of the root.
LEVEL
0
A
B C D 1
E F G H I J 2
3
K L M
The root contains A, and we normally draw trees with the root at the top.
The number of childs of a node is called its degree. The degree of A is 3 and C is 1.
Nodes that have degree zero are called terminal nodes (K, L, M, etc.) or leaf nodes.
A is a parent node of child nodes (B, C, D). childs of the same parent are said to be
siblings.
The degree of the tree is the max degree of the nodes in the tree.
The level of a node is defined by initially letting the root be at level Zero. If a node is at
level P, then its children are at level at P+1.
The height or depth of a tree is defined to be the max level of any node in the tree.
is a A forest set of n>=0 disjoint trees.
BINARY TREES
A binary tree is a finite set of nodes that is either empty or consists of a root and two
disjoint binary trees called the left and right subtrees.
B
B C 1
C
D E F G 2
D
H I 3
E
(a). Skewed Tree (b). Complete Binary Tree
The binary tree of depth k having exactly 2k – 1 nodes is called a full binary tree of depth k.
B C
D E F G
(b). Full Binary Tree of depth 3
If a complete binary tree with n nodes is represented sequentially, then for any node with
index i, 1<=i<=n, we have
parent (i) is at [i/2] if i#1 when i=1, i is the root and has no parent
left child (i) is at 2i if 2i<n if (2i >n), i has no left child
right child (i) is at 2i+1 if 2i + 1 <n if (2i+1 >n), i has no right child
Sequential representation of binary tree
If left child -> 2i position
If right child -> 2i+1 position
A A A
B
B C B C
C
D E F G D E F
D
H I D
E
A B C D E F G H I A B C D E A B C D E F G
1 2 3 4 5 6 7 8 9 1 2 3 4 8 - 1 1 2 3 4 6 7 - 1
6 5
To represent the binary tree using linked lists, we use the concept of doubly linked
list, consisting of two pointers, a left pointer pointing to left child and a right pointer pointing
to the right child. If a node doesn’t have left or right child the corresponding fields are
NULL.
A B C
D E F G
B C
H I
D \ E \ \ F \ \ G \
\ H \ \ I \
BINARY SEARCH TREE
A binary search tree can support the operations search, insert and delete.
Consider a tree below with the values 30, 5, 40, 2
Now insert 80 into tree Now insert 35 into tree
3 3 3
0 0 0
5 4 5 4 5 4
0 0 0
2 2 8 2 3 8
0 5 0
Now Delete 30 from tree Now Delete 30 from tree
5 4 (or) 5 4 2 4
0 0 0
8 3 8 3 8
2 2
0 5 0 5 0
Here 5 is moved up to root and after that 5 is deleted
4 15
3 9 18
16 20
BINARY TREE TRAVERSALS
start
start
B C B C
D E F G D E F G
H I J H I J
K K
BINARY TREE
PREORDER : A B D E H C F GI K J
A A
B C B C
D E F G D E F G
start H I J start H I J
K K
POSTORDER :D H E B F H I J G C A
INORDER : D B H E A F C K I
GJ
16. GRAPHS
A graph G is defined as G={V,E} where
The set V is a finite, non empty set of vertices
The set E is a set of pairs of vertices, these pairs are called edges
The notations V(G) and E(G) represents the sets of vertices and edges.
G=(V,E) to represent a graph.
In an undirected graph the pairs of vertices representing any edge is unordered. Thus the
pairs (u,v) and (v, u) represent same edge.
V(G2)={1,2,3,4,5,6,7}
V(G1)={1,2,3,4} 1
1 Set of vertices
Set of vertices
E(G1)={(1,2),(1,3),(2,4),
2 3 E(G1)={(1,2),(1,3),(1,4),(2,3),(2,4),(3,4)2 3
} (2,5),(3,6),(3,7)}
In a directed graph each edge is represented by a directed pair (u,v) u is a tail and v the
head of edge.
Therefore (u, v) and (v, u) are different edges.
3 Here (1,2) & (2,1) are not same they are different edges
G3
eg: 1 2
edge on vertex 1 is a self edge
3
G4
A path from vertex u to vertex v in graph G is a sequence of vertices u, i1, i2, ----ik, v such
that (u,i1), (i1,i2) ---(Ik,v) are edges in E(G)
A simple path is a path in which all vertices except possibly the first and last are distinct.
A cycle is a simple path in which the first and last vertices are same
The path 1,2,3,1 is a cycle in G1
The path 1,2,1 is a cycle in G3
The degree of a vertex is the number of edges incident on to that vertex
The degree of vertex 1 in G1 is 3
The in degree of a vertex v is the number of incoming edges
The out degree of a vertex v is the number of outgoing edges
Degree of a vertex v = in degree of v + out degree of v
Vertex 2 of G3 has In degree 1, Out degree 2, Degree 3
GRAPH REPRESENTATIONS
Adjacency matrix
Adjacency lists
Adjacency multilists
Let G=(V,E) be a graph with n vertices , n>=1. The adjacency matrix of G is a two
dimensional n*n array,
say a with the property a[i,j] =1 iff the (i,j) & (i,j) (directed graph) is in E(G)
a[i,j] =0 if there is no such edge in G
from adjacency matrix, we can readily determine whether there is an edge connecting any
two vertices i and j.
1 2 3 4
1
1 0 1 1 1
2 3 2 1 0 1 1
3 1 1 0 1
4 4 1 1 1 0
Adjacency matrix
1
1 2 3
2 1 0 1 0
1 0 1
2
3 0 0 0
Adjacency matrix
3
for a directed graph the row sum is the out degree, col. sum is the in degree
Adjacency lists:
The n rows of adjacency matrix are represented as n linked lists
There is one list for each vertex in G the nodes in the list i represent the vertices that are
adjacent from vertex i.
Each node has two fields’ vertex and link.
4 2 3 0
1
1
3 4 1 0
2 3
2
2 4 1 0
4
1 2 3 0
GRAPH TRAVERSALS
Breadth first search can be used to find the shortest distance from some starting node to the
remaining nodes of the graph.
This shortest distance is the minimum number of edges traversed in order to travel from
the start node to the specific node
Starting at a node v, this distance is calculated by examining all incident edges to node v
and then moving on to an adjacent node w and repeating the process
The traversal continuous till all nodes in the graph are examined or no new node is
visited in the last iteration.
0 A
Apply BFS :
A
2 B C D E
1 1
B C D E
F
2 BFS Spanning Tree
F
2
BFS Traversal : A C E B D F
If BFS is used on a connected undirected graph G, then all vertices in G get visited and graph
is traversed
If G is not connected, then at last, at least one vertex of G is not visited.
Adjacency list for graph
2 3 \
2 3 1
1 4 5 \
2 1 6 7 \
4 5 6 7
3 2 8 \
2 8 \
8
4
3 8 \
5 3 8 \
2 8 2 8 \
6
7
8
BFS traversing for above graph BFS Spanning tree
1 1
1 1
2 4 3 4 2 3
2 2 1 1
1 1
4 5 6 7 4 5 6 7
3 8 8
1
5 6
F F
4
Unit V: Searching and Sorting(co3)
Finding whether a required element is there or not in the given list of elements is
known as searching.
LINEAR SEARCH
Search starts at the beginning of the list and search for the element until a match is
found or the list is completed without a match.
In the best case, the element will be found in the first comparison. Hence best case
complexity = O(1).
If there are n items in the list, then in the worst case (i.e when the element required is not
there in the list) n comparisons are needed. Hence Worst case complexity = O(n).
The avg case is also proportional to n and Avg case complexity = O(n).
Program – Linear search
#define size 10
int a[size],last=-1;
int l_search(int);
void main()
{
int key,position,x;
do
{
printf("Enter A Value, (0) to Stop : “);
scanf("%d",&x);
if(x!=0)
a[++last]=x;
}while(x!=0&&last<size-1);
printf("enter the element to be searched");
scanf("%d",&key);
position=l_search(key);
if(position==-1)
printf("un successful search\n");
else
printf("element found in %d location",position);
}
Each time the comparison is made ,and if it is not the success then the list is divided into
parts and the search continues in one of them.
The search requires at most log n comparisons.Hence both average and worst cases of a
binary search is proportional to log2N i.e O(log n)
Best case of theBinary search comes when the target is found in the first comparison only.
Hence best case complexity = O(1).
#define size 10
int a[size],key,last;
int bsearch(int,int,int);
void main()
{
int position,x;
do
{
printf("Enter A Value, (0) to Stop : “);
scanf("%d",&x);
if(x!=0)
a[++last]=x;
}while(x!=0&&last<size-1);
printf("enter the element to found");
scanf("%d",&key);
position=bsearch(0,last,key);
if(position==-1)
printf("un successful search");
else
printf("element is found in %d position",position);
}
Selection sort
In this sort, in each iteration it will search the list to find the smallest element. Then it
swaps this with the first element in the list and process continues with the remaining list , till
the list is arranged in a sorted order.
The number of comparisons needed is n-1 in the first iteration, n-2 in the second iteration,
n-3 in the third iteration, and so on and n-i in the ithiteration. Hence there are at most (n-
1)+(n-2)+-----+1=n(n-1)/2 comparisons, time complexity is O(n2).
In the ith iteration the algorithm finds the lowest element A[I],A[I+1],…..A[n], and swaps
it with A[I]. It means, for each pass I, selection sort ensures that the elements in positions 1
to I are in sorted order.
Example :
Suppose A is the array of 12 elements:
Consider the first element in the list as PIVOT, L and R are the left and right indexes.
Position R at the last element, i.e., Infinity which we will suffix to the given list as shown
below.
Note: Underscore( _ ) represents L element and Bar represents R element.
pivot L R
44 33 11 55 77 90 40 60 99 22 88 66
step 1: from the L search for the big element towards R, and from the R search for small
element towards L.
L R
44 33 11 55 77 90 40 60 99 22 88 66
if L<R then swap elements at L and R and continue step 1 until L>R. In this
occurrence 55 and 22 will be swapped. And the process continues..
L R
44 33 11 22 77 90 40 60 99 55 88 66
44 33 11 22 77 90 40 60 99 55 88 66
44 33 11 22 40 90 77 60 99 55 88 66
R L
44 33 11 22 40 90 77 60 99 55 88 66
Here L>R and so stop searching, Now when L>R swap the PIVOT element with R element.
40 33 11 22 44 90 77 60 99 55 88 66
First List Second List
Now the PIVOT element is in its correct position. Such that all elements in the left of
PIVOT are less than that. And all elements in the right are greater than PIVOT. This will
form two sub-lists, one to the left of the PIVOT and another to the right of PIVOT.Now
Repeat the above process for the first list, then for the second list until a sub-list contains only
one element which need not to be sorted.
Program – QUICK SORT:
#define size 20
int a[size];
void q_sort(int,int);
int partition(int,int);
void main()
{
int i=0,x,j;
do
{
printf("Enter a value, (0) to Stop : ");
scanf("%d",&x);
if(x!=0) a[i++]=x;
}while(x!=0&&i<size);
q_sort(0,i-1);
for(j=0;j<=i-1;j++)
printf("%3d",a[j]);
}
t=a[pivot];
a[pivot]=a[r];
a[r]=t;
return r;
}
Merge sort
This is a sorting algorithm which will use divide and conquer strategy. In this method, in
each step the list will be divided into two equal parts and individually sorted and then will be
combined into the required list. For sorting the sub-lists we will use the same approach if the
list contains more than one element.
1. The time complexity of merge sort is O(NlogN) for all cases.
2. This needs extra memory for merging purpose.
Program :
#include<stdio.h>
#define size 20
int a[size];
void m_sort(int,int);
void merge(int,int,int);
void main()
{
int i=0,x,j;
do
{
printf("Enter a value, (0) to Stop : ");
scanf("%d",&x);
if(x!=0)
a[i++]=x;
} while(x!=0&&i<size);
m_sort(0,i-1);
printf("Sorted Order is : ");
for(j=0;j<=i-1;j++)
printf("%3d",a[j]);
}