Sei sulla pagina 1di 41

Data Structure Introduction

In the modern world, Data and its information is an essential part, and various
implementations are being made to store in different ways. Data are just a collection of facts
and figures, or you can say data are values or a set of values that are in a particular format. A
data item refers to a single set of values. Data items are then further categorized into sub-items
which are the group of items which are not being called a plain elementary form of items. Let
us take an example where the name of the student may be divided into three sub-items
namely: first name, middle name and last name. But the ID that is assigned to a student would
normally be considered as a single item.

In the example mentioned above such as ID, Age, Gender, First

What is Data Structure?


In computer terms, a data structure is a Specific way to store and organize data in a
computer's memory so that these data can be used efficiently later. Data may be arranged in
many different ways such as the logical or mathematical model for a particular organization of
data is termed as a data structure. The variety of a specific data model depends on the two
factors -

 Firstly, it must be loaded enough in structure to reflect the actual relationships of the
data with the real world object.

 Secondly, the formation should be simple enough so that anyone can efficiently process
the data each time it is necessary.

Categories Of Data Structure


The data structure can be subdivided into major types:

 Linear Data Structure

 Non-linear Data Structure

Linear Data Structure


A data structure is said to be linear if its elements combine to form any specific order.
There are two techniques of representing such linear structure within memory.

 The first way is to provide the linear relationships among all the elements represented
using linear memory location. These linear structures are termed as arrays.

 The second technique is to provide a linear relationship among all the elements
represented by using the concept of pointers or links. These linear structures are termed
as linked lists.

The common examples of the linear data structure are:

 Arrays

 Queues

 Stacks

 Linked lists

Non-Linear Data Structure


This structure is mostly used for representing data that contains a hierarchical
relationship among various elements.

Examples of Non-Linear Data Structures are listed below:

 Graphs

 the family of trees and

 table of contents

Tree: In this case, data often contain a hierarchical relationship among various elements. The
data structure that reflects this relationship is termed as a rooted tree graph or a tree.

Graph: In this case, data sometimes hold a relationship between the pairs of elements which is
not necessarily following the hierarchical structure. Such a data structure is termed as a Graph.

Fundamental Elements Of Data Structure


The present generation digital computer was made and planned as a device which can
make easy and speed up complex and time-consuming computations. In the majority of
applications or programs, it can store and access a huge amount of information take part as the
dominant one and is measured to be its primary feature and its ability to compute, that is to
calculate or to carry out arithmetic, has in many cases become almost unrelated.

In most of the cases, the vast amount of information which is to be developed in some
sense signifies a concept of a part of reality. The information that is accessible to the computer
consists of a specific set of data about the real problem that is set that and is considered
applicable to the problem at hand. The data signifies an abstraction of reality in the sense which
certain properties and distinctiveness of the real objects get ignored as they are peripheral and
inappropriate to the particular problem. A concept of abstraction is thereby also an overview of
facts.

In this chapter, you will learn about the fundamental elements of the data structure.

What are the characteristics of Data types in Data Structure?


 The data type chooses the set of values to which a constant will belong and which may
be assumed by a variable or an expression within a program or which may be produced
by an operator or a function.

 The type of a value indicated by a constant or a variable or expression may be resulting


from its form or its declaration without the need of executing the computational
process.

 Each operator and function expects some arguments of a fixed type which is
represented by assigning a data type to those specific sets of arguments and yields a
result of a fixed type. If an operator declares arguments of several types such as the '+'
will be used for addition of both integers and real numbers, then the type of the answer
can be determined from specific language rules.

Types of Data Structures


In this case, you will be studying the concepts of the data structure using C++. The Datatypes
are mainly categorized into three major types. These are:

 Built-in data type: These types of data types are predefined and has a fixed set of rules for
declaration. In other words, these data types when belonging to a particular programming
language has built-in support, and hence they are also called as built-in data types. Examples of
such data types are:

1. Integer type

2. Boolean type

3. Character type

4. Floating type

 Derived Data type: These data types can be implemented independently within a
language. These data types are built by combining both primary and built-in data types
and then associating operations on them. Examples of such data types are:
5. Array

6. Stack

7. Queue

8. List

You might be familiar with these basic data types if you have read either C or C++. For
dealing with the various concepts of data structures, you can use any programming language.
But it is recommended to use either C or C++ for better implementation purpose.

Basic Operations of Data Structures


Some specific operations process all data in the data structures. The specific data
structure that has been chosen mostly depends on the number of time of the occurrence of the
operation which needs to be carried out on the data structure. Names of such operations are
listed below:

 Traversing

 Searching

 Insertion

 Deletion

 Sorting

 Merging

Data Structures and Arrays


You have seen so far that data structure uses some algorithms and need storage for
storing values. For storing these values, programmers must need to have the fundamental data
type's names such as char, int, float & double. As you know, these particular data types are
beneficial for declaring variables, constants or a return type for a function; they are in control
by the fact that, these types can store only a specific form of value at a time. For many
applications, there may arise some circumstances where programmers need to have a single
name to store multiple values. For processing such a large amount of data, programmers need
powerful data types that would facilitate efficient storage, accessing and dealing with such data
items. Using C++, you can implement the concept of arrays.

What are arrays?


The array is a fixed-size sequenced collection of variables belonging to the same data
types. The array has adjacent memory locations to store values. Since the array provides a
convenient structure for representing data, it falls under the category of the data structures in
C. The syntax for declaring array are:

data_type array_name [array_size];

Following are the essential terminologies used for understanding the concepts of Arrays:

Element: Every item stored in an array is termed as an element

Index: each memory location of an element in an array is denoted by a numerical index which is
used for identifying the element

Why Do You Need Arrays for Building a Specific Data Structure?


When a program works with many variables which hold comparable forms of data, then
organizational and managerial difficulty quickly arise. If you are not using arrays, then the
number of variables used will increase. Using the array, the number of variables reduces, i.e.,
you can use a single name for multiple values, you need to deal with its index values (starting
from 0 to n).

So if the total run of each player is getting stored in separate variables, using arrays you
can bring them all into one array having single name like: plrscore[11];

Collecting Input Data in Arrays


Arrays are particularly helpful for making a collection of input data which arrive in
random order. An excellent example will be vote counting: You can write a program which
tallies the votes of a four-candidate in an election. (For your ease, you will say use the
candidates' names as Cand 0, Cand 1, Cand 2, and Cand 3.) Votes arrive once at a time, where a
vote for Candidate i is denoted by the number, i. So according to this example, two votes for
Cand 3 followed by one vote for Cand 0 would appear:

0
and so on....

i.e., the structure will be:

int votes[4];

Basic Operations
There is some specific operation that can be performed or those that are supported by
the array. These are:

 Traversing: It prints all the array elements one after another.

 Inserting: It adds an element at given index.

 Deleting: It is used to delete an element at given index.

 Searching: It searches for an element(s) using given index or by value.

 Updating: It is used to update an element at given index.

concept Of Stack in Data Structure


In this chapter, you will explore one of the most important data structures which are
used in many fields of programming and data handling, i.e., the Stack. It falls under the category
of an abstract data type which serves as a concrete and valuable tool for problem-solving. In
this chapter, you will study the various operations and working technique of stack data
structure.

What is stack?
A stack is a linear data structure in which all the insertion and deletion of data or you
can say its values are done at one end only, rather than in the middle. Stacks can be
implemented by using arrays of type linear.

The stack is mostly used in converting and evaluating expressions in Polish notations, i.e.:

 Infix

 Prefix

 Postfix

In case of arrays and linked lists, these two allows programmers to insert and delete
elements from any place within the list, i.e., from the beginning or the end or even from the
middle also. But in computer programming and development, there may arise some situations
where insertion and deletion require only at one end wither at the beginning or end of the list.
The stack is a linear data structure, and all the insertion and deletion of its values are done in
the same end which is called the top of the stack. Let us suppose take the real-life example of a
stack of plates or a pile of books etc. As the item in this form of data structure can be removed
or added from the top only which means the last item to be added to the stack is the first item
to be removed. So you can say that the stack follows the Last In First Out (LIFO) structure.

Stack as Abstract Data Type


He stacks of elements of any particular type is a finite sequence of elements of that type
together with the following operations:

 Initialize the stack to be empty

 Determine whether the stack is empty or not

 Check whether the stack is full or not

 If the stack is not full, add or insert a new node at the top of the stack. This operation is
termed as Push Operation

 If the stack is not empty, then retrieve the node at its top

 If the stack is not empty, the delete the node at its top. This operation is called as Pop
operation

Write a C program to illustrate Stack Operation using Arrays.


#include<stdio.h>
#include<conio.h>
#define SIZE 5
void push(int);
void pop();
void display();
int a[5],top=-1;
void main()
{
intitem,choice;
clrscr();
for(;;)
{
printf("\n\n******MENU******\n\n");
printf("1.Push\n2.Pop\n3.Display\n4.Exit\n");
printf("Enter your Choice\n");
scanf("%d",&choice);
switch(choice)
{
case 1:printf("Enter the value to be inserted\n");
scanf("%d",&item);
push(item);
break;
case 2:pop();
break;
case 3:display();
break;
case 4:exit(0);
break;
default:printf("enter the correct choice\n");
break;
}
}
}
void push(int item)
{
if(top==SIZE-1)
printf("Stack overflow\n");
else
{
top=top+1;
a[top]=item;
printf("Insertion success\n");
}
}
void pop()
{
if(top==-1)
printf("stack is empty\n");
else
{
printf("Deleted item is=%d",a[top]);
top=top-1;
}
}
void display()
{
if(top==-1)
printf("stack is empty\n");
else
{
int i;
printf("Elements in stack are:\n");
for(i=top;i>=0;i--)
printf("%d\n",a[i]);
}
getch();
}

Write a C program to evaluate a POSTFIX expression using stack operations.

#include<stdio.h>
int stack[20];
int top = -1;

void push(int x)
{
stack[++top] = x;
}

int pop()
{
return stack[top--];
}

int main()
{
charexp[20];
char *e;
int n1,n2,n3,num;
printf("Enter the valid postfix expression :: ");
scanf("%s",exp);
e = exp;
while(*e != '\0')
{
if(isdigit(*e))
{
num = *e - 48;
push(num);
}
else
{
n1 = pop();
n2 = pop();
switch(*e)
{
case '+':
{
n3 = n1 + n2;
break;
}
case '-':
{
n3 = n2 - n1;
break;
}
case '*':
{
n3 = n1 * n2;
break;
}
case '/':
{
n3 = n2 / n1;
break;
}
}
push(n3);
}
e++;
}
printf("\nThe result of expression %s = %d\n\n",exp,pop());
return 0;

}
Concepts of Queue in Data Structure
The queue is a linear data structure used to represent a linear list. It allows insertion of
an element to be done at one end and deletion of an element to be performed at the other
end.

In this chapter, you will be given an introduction to the basic concepts of queues along
with the various types of queues which will be discussed simulating the real world situation.

What is a Queue?
A queue is a linear list of elements in which deletion of an element can take place only
at one end called the front and insertion can take place on the other end which is termed as the
rear. The term front and rear are frequently used while describing queues in a linked list. In this
chapter, you will deal with the queue as arrays.

In the concept of a queue, the first element to be inserted in the queue will be the first
element to be deleted or removed from the list. So Queue is said to follow the FIFO (First In
First Out) structure. A real-life scenario in the form of example for queue will be the queue of
people waiting to accomplish a particular task where the first person in the queue is the first
person to be served first.

Other examples can also be noted within a computer system where the queue of tasks
arranged in the list to perform for the line printer, for accessing the disk storage, or even in the
time-sharing system for the use of CPU. So basically queue is used within a single program
where there are multiple programs kept in the queue or one task may create other tasks which
must have to be executed in turn by keeping them in the queue.

Queue as an ADT (Abstract Data Type)


The meaning of an abstract data type clearly says that for a data structure to be
abstract, it should have the below-mentioned characteristics:

 First, there should be a particular way in which components are related to each other

 Second, a statement for the operation that can be performed on elements of abstract
data type must have to be specified
Thus for defining a Queue as an abstract data type, these are the following criteria:

 Initialize a queue to be empty

 Check whether a queue is empty or not

 Check whether a queue is full or not

 Insert a new element after the last element in a queue, if the queue is not full

 Retrieve the first element of the queue, if it is not empty

 Delete the first element in a queue, if it is not empty

Write a C program to implement queue using arrays

#include<stdio.h>
#include<conio.h>
#define SIZE 5
void insert(int);
void Delete();
void display();

int a[5],r=-1,f=-1;
void main()
{
intitem,choice;
clrscr();
for(;;)
{
printf("\n\n***MENU***\n\n");
printf("1.Insert\n2.Delete\n3.Display\n4.Exit\n");
printf("Enter your choice\n");
scanf("%d",&choice);
switch(choice)
{
case 1:printf("enter the item to be inserted\n");
scanf("%d",&item);
insert(item);
break;
case 2:Delete();
break;
case 3:display();
break;
case 4:exit(0);
break;
}
}
}
void insert(int item)
{
if(r==SIZE-1)
printf("queue overflow\n");
else
{
r=r+1;
a[r]=item;
printf("Insertion successful\n");
f=0;
}
}
void Delete()
{
if(f==-1 || f>r)
printf("queue is empty");
else
{
printf("Deleted item is %d",a[f]);
f=f+1;
}
}
void display()
{
if(f==-1 || f>r)
printf("queue is empty");
else
{
int i;
printf("elements in queue are:\n");
for(i=f;i<=r;i++)
printf("%d\n",a[i]);
}
getch();
}
Searching Techniques
This chapter explores various searching techniques. The process of identifying or finding
a particular record is called Searching. You often spend time in searching for any desired item. If
the data is kept properly in sorted order, then searching becomes very easy and efficient. In this
chapter, you will get to know the basic concepts of searching that are used in the data structure
and case of programming also.

What is searching?
Searching is an operation or a technique that helps finds the place of a given element or
value in the list. Any search is said to be successful or unsuccessful depending upon whether
the element that is being searched is found or not. Some of the standard searching technique
that is being followed in the data structure is listed below:

 Linear Search or Sequential Search

 Binary Search

What is Linear Search?


This is the simplest method for searching. In this technique of searching, the element to
be found in searching the elements to be found is searched sequentially in the list. This method
can be performed on a sorted or an unsorted list (usually arrays). In case of a sorted list
searching starts from 0th element and continues until the element is found from the list or the
element whose value is greater than (assuming the list is sorted in ascending order), the value
being searched is reached.

As against this, searching in case of unsorted list also begins from the 0th element and
continues until the element or the end of the list is reached.

The list given above is the list of elements in an unsorted array. The array contains ten
elements. Suppose the element to be searched is '46', so 46 is compared with all the elements
starting from the 0th element, and the searching process ends where 46 is found, or the list
ends.
The performance of the linear search can be measured by counting the comparisons done to find out an
element. The number of comparison is 0(n).

Algorithm for Linear Search

It is a simple algorithm that searches for a specific item inside a list. It operates looping
on each element O(n) unless and until a match occurs or the end of the array is reached.
 algorithm Seqnl_Search(list, item)

 Pre: list != ;

 Post: return the index of the item if found, otherwise: 1

 index <- fi

 while index < list.Cnt and list[index] != item //cnt: counter variable

 index <- index + 1

 end while

 if index < list.Cnt and list[index] = item

 return index

 end if

 return: 1

 end Seqnl_Search

Write a C Program To Search a given number using linear search with their
complexity.

#include<stdio.h>
#include<conio.h>
#include<time.h>
void main()
{
int a[10],i,n,key,flg;
clock_tstime,etime;
double tm;
clrscr();
printf("Enter the size of array\n");
scanf("%d",&n);
printf("Enter the %d Array elements ",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the key element to be searched\n");
scanf("%d",&key);
stime=clock();
for(i=0;i<n;i++)
{
if(a[i]==key)
flg=1;
}
etime=clock();
tm=(stime-etime)/CLK_TCK;
if(flg==1)
printf("Key element found\n");
else
printf("Key element not found\n");
printf("The duration taken to execute is %f",tm);
getch();
}

What is Binary Search?


Binary search is a very fast and efficient searching technique. It requires the list to be in
sorted order. In this method, to search an element you can compare it with the present
element at the center of the list. If it matches, then the search is successful otherwise the list is
divided into two halves: one from the 0th element to the middle element which is the center
element (first half) another from the center element to the last element (which is the 2nd half)
where all values are greater than the center element.

The searching mechanism proceeds from either of the two halves depending upon
whether the target element is greater or smaller than the central element. If the element is
smaller than the central element, then searching is done in the first half, otherwise searching is
done in the second half.

Algorithm for Binary Search

 algorithm Binary_Search(list, item)

 Set L to 0 and R to n: 1

 if L > R, then Binary_Search terminates as unsuccessful

 else

 Set m (the position in the mid element) to the floor of (L + R) / 2

 if Am < T, set L to m + 1 and go to step 3

 if Am > T, set R to m: 1 and go to step 3

 Now, Am = T,

 the search is done; return (m)

Write a C program to search a given number using Binary search


#include<stdio.h>
#include<conio.h>
voidbsearch(int ,int a[],int ,int *);
void main()
{
inti,n,item,a[20],pos;
clrscr();
printf("Enter the size of array\n");
scanf("%d",&n);
printf("Enter the array elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the key element\n");
scanf("%d",&item);
bsearch(item,a,n,&pos);
if(pos==-1)
printf("Item not found\n");
else
printf("Item found at %d position \n",pos);
getch();
}
voidbsearch(intitem,int a[],intn,int *pos)
{
intlow,high,mid;
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(item==a[mid])
{
*pos=mid;
return;
}
if(item<a[mid])
high=mid-1;
else
low=mid+1;
}
*pos=-1;
}

Sorting Techniques
In this chapter you will be dealing with the various sorting techniques and their
algorithms used to manipulate data structure and its storage. Sorting method can be
implemented in different ways - by selection, insertion method, or by merging. Various types
and forms of sorting methods have been explored in this tutorial.

What is sorting?
Sorting refers to the operation or technique of arranging and rearranging sets of data in
some specific order. A collection of records called a list where every record has one or more
fields. The fields which contain a unique value for each record is termed as the key field. For
example, a phone number directory can be thought of as a list where each record has three
fields - 'name' of the person, 'address' of that person, and their 'phone numbers'. Being unique
phone number can work as a key to locate any record in the list.

Sorting is the operation performed to arrange the records of a table or list in some order
according to some specific ordering criterion. Sorting is performed according to some key value
of each record.

The records are either sorted either numerically or alphanumerically. The records are
then arranged in ascending or descending order depending on the numerical value of the key.
Here is an example, where the sorting of a lists of marks obtained by a student in any particular
subject of a class.

Categories of Sorting
The techniques of sorting can be divided into two categories. These are:

 Internal Sorting

 External Sorting

Internal Sorting: If all the data that is to be sorted can be adjusted at a time in the main
memory, the internal sorting method is being performed.

External Sorting: When the data that is to be sorted cannot be accommodated in the memory
at the same time and some has to be kept in auxiliary memory such as hard disk, floppy disk,
magnetic tapes etc, then external sorting methods are performed .

The Complexity of Sorting Algorithms


The complexity of sorting algorithm calculates the running time of a function in which 'n'
number of items are to be sorted. The choice for which sorting method is suitable for a problem
depends on several dependency configurations for different problems. The most noteworthy of
these considerations are:

 The length of time spent by the programmer in programming a specific sorting program

 Amount of machine time necessary for running the program

 The amount of memory necessary for running the program

The Efficiency of Sorting Techniques


To get the amount of time required to sort an array of 'n' elements by a particular
method, the normal approach is to analyze the method to find the number of comparisons (or
exchanges) required by it. Most of the sorting techniques are data sensitive, and so the metrics
for them depends on the order in which they appear in an input array.

Various sorting techniques are analyzed in various cases and named these cases as follows:

 Best case

 Worst case

 Average case

Hence, the result of these cases is often a formula giving the average time required for a
particular sort of size 'n.' Most of the sort methods have time requirements that range from
O(nlog n) to O(n2).

Types of Sorting Techniques


 Bubble Sort

 Selection Sort

 Merge Sort

 Insertion Sort

 Quick Sort

 Heap Sort

Bubble Sort
Bubble Sort Algorithm is used to arrange N elements in ascending order, and for that,
you have to begin with 0th element and compare it with the first element. If the 0th element is
found greater than the 1st element, then the swapping operation will be performed, i.e., the
two values will get interchanged. In this way, all the elements of the array get compared.

Below given figure shows how Bubble Sort works:

Algorithm for Bubble Sort

1. algorithm Bubble_Sort(list)

2. Pre: list != fi

3. Post: list is sorted in ascending order for all values

4. for i <- 0 to list:Count - 1

5. for j <- 0 to list:Count - 1

6. if list[i] < list[j]


7. Swap(list[i]; list[j])

8. end if

9. end for

10. end for

11. return list

12. end Bubble_Sort

Write a C program to sort an array using bubble sort with their complexity
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],n,i,j,temp;
clrscr();
printf("Enter the size of array\n");
scanf("%d",&n);
printf("Enter the elements %d array elements",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(j=1;j<n;j++)
{
for(i=0;i<n-j;i++)
{
if(a[i]>a[i+1])
{
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}
}
printf("Sorted Array elements are\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
getch();
}

Selection Sort
The selection is a straightforward process of sorting values. In this method, to sort the
data in ascending order, the 0th element is compared with all other elements. If the 0th
element is found to be greater than the compared element, the two values get interchanged. In
this way after the first iteration, the smallest element is placed at 0th position. The technique is
repeated until the full array gets sorted.

The below-given figure shows how Selection Sort works:

Write a C program to sort an array using selection sort


#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],i,j,n,pos,temp;
clrscr();
printf("Enter the size of Array\n");
scanf("%d",&n);
printf("Enter the %d Array elements\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n-1;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if(a[j]<a[pos])
pos=j;
}
temp=a[pos];
a[pos]=a[i];
a[i]=temp;
}
printf("Sorted elements are\n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
getch();
}

Merge Sort
Merge sort is another sorting technique and has an algorithm that has a reasonably
proficient space-time complexity - O(n log n) and is quite trivial to apply. This algorithm is based
on splitting a list, into two comparable sized lists, i.e., left and right and then sorting each list
and then merging the two sorted lists back together as one.
Merge sort can be done in two types both having similar logic and way of implementation.
These are:

 Top down implementation

 Bottom up implementation

Below given figure shows how Merge Sort works:


Algorithm for Merge Sort

1. algorithm Merge_Sort(list)

2. Pre: list 6= fi

3. Post: list has been sorted into values of ascending order

4. if list.Count = 1 // when already sorted

5. return list

6. end if

7. m <- list.Count = 2

8. left <- list(m)

9. right <- list(list.Count - m)

10. for i <- 0 to left.Count - 1

11. left[i] <- list[i]

12. end for


13. for i <- 0 to right.Count -1

14. right[i] <- list[i]

15. end for

16. left <- Merg_Sort(left)

17. 17) right <- Merge_Sort(right)

18. 18) return MergeOrdered(left, right)

19. 19) end Merge_Sort

Sort a given set of elements using the Merge sort method and determine the
time required to sort the elements. Repeat the experiment for different values
of n.
#include<stdio.h>
void disp( );
void mergesort(int,int,int);
void merge(int,int);
int a[50],n;
void main( )
{
int i;
clrscr( );
printf("\nEnter the n value:");
scanf("%d",&n);
printf("\nEnter elements for an array:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nBefore Sorting the elements are:");
disp( );
merge(0,n-1);
printf("\nAfter Sorting the elements are:");
disp( );
getch( );
}
void disp( )
{
int i;
for(i=0;i<n;i++)
printf("%d ",a[i]);
}
void mergesort(int low,int mid,int high)
{
int t[50],i,j,k;
i=low;
j=mid+1;
k=low;
while((i<=mid) && (j<=high))
{
if(a[i]>=a[j])
t[k++]=a[j++];
else
t[k++]=a[i++];
}
while(i<=mid)
t[k++]=a[i++];
while(j<=high)
t[k++]=a[j++];
for(i=low;i<=high;i++)
a[i]=t[i];
}
void merge(int low,int high)
{
int mid;
if(low!=high)
{
mid=((low+high)/2);
merge(low,mid);
merge(mid+1,high);
mergesort(low,mid,high);
}
}

Quick Sort
Quick sort is one of the most famous sorting algorithms based on divide and conquers
strategy which results in an O(n log n) complexity. So, the algorithm starts by picking a single
item which is called pivot and moving all smaller items before it, while all greater elements in
the later portion of the list. This is the main quick sort operation named as a partition,
recursively repeated on lesser and greater sublists until their size is one or zero - in which case
the list is wholly sorted. Choosing an appropriate pivot, as an example, the central element is
essential for avoiding the severely reduced performance of O(n2).

Algorithm for Quick Sort

1. algorithm Quick_Sort(list)
2. Pre: list 6= fi

3. Post: the list has been sorted in ascending order

4. if list.Count = 1 // list already sorted

5. return list

6. end if

7. pivot <- Median_Value(list)

8. for i <- 0 to list.Count - 1

9. if list[i] = pivot

10. equal.Insert(list[i])

11. end if

12. if list[i] < pivot

13. less.Insert(list[i])

14. end if

15. if list[i] > pivot

16. greater.Insert(list[i])

17. end if

18. end for

19. return Concatenate(Quick_Sort(less), equal, Quick_Sort(greater))

20. end Quick_sort.

Sort a given set of elements using the Quick sort method and determine the
time required to sort the elements. Repeat the experiment for different values
of n.

#include<stdio.h>
#include<time.h>
void qsort(int[],int,int);
int partition(int[],int,int);
void main()
{
int a[20],i,n;
clock_t s,e;
clrscr();
printf("Enter the value of n");
scanf("%d",&n);
printf("Enter the array elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
a[i]=rand()%100;
printf("\n The array elements before\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
s=clock();
delay(100);
qsort(a,0,n-1);
e=clock();
printf("\n Elements of the array after sorting are...\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
printf("\n Time taken:%f",e-s/CLK_TCK);
getch();
}

void qsort(int a[],int low,int high)


{
int j;
if(low<high)
{
j=partion(a,low,high);
qsort(a,low,j-1);
qsort(a,j+1,high);
}
}
int partion(int a[],int low,int high)
{
int pivot,i,j,temp;
pivot=a[low];
i=low+1;
j=high;
while(1)
{
while(pivot>a[i] &&i<=high)
i++;
while(pivot<a[j])
j--;
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
else
{
temp=a[j];
a[j]=a[low];
a[low]=temp;
return j;
}
}
}

Insertion Sort
Insertion sort is a to some extent an interesting algorithm with an expensive runtime
characteristic having O(n2). This algorithm can be best thought of as a sorting scheme which
can be compared to that of sorting a hand of playing cards, i.e., you take one card and then look
at the rest with the intent of building up an ordered set of cards in your hand.

Algorithm for insertion Sort

1. algorithm Insertion_sort(list)

2. Pre: list 6= fi

3. Post: list has been sorted into values of ascending order

4. unsorted <- 1

5. while unsorted < list.Count


6. hold <- list[unsorted]

7. i à unsorted - 1

8. while i >= 0 and hold < list[i]

9. list[i + 1] <- list[i]

10. i <- i - 1

11. end while

12. list[i + 1] <- hold

13. unsorted <- unsorted + 1

14. end while

15. return list

16. end Insertion_sort

Write a program to implement insertion sort using decrease and conquer


technique
#include<stdio.h>
#include<conio.h>
#include<time.h>
void insertion_sort(int x[],int n)
{
int i,j,place;
for(i=0;i<n;i++)
{
place=x[i];
j=i-1;
while(j>=0 && place<x[j])
{
x[j+1]=x[j];
j--;
}
x[j+1]=place;
}
}
void main()
{
int size,k;
int a[30];
clrscr();
printf("Enter the size\n");
scanf("%d",&size);
printf("\n Enter %d integers to sort\n",size);
for(k=0;k<size;k++)
scanf("%d",&a[k]);
insertion_sort(a,size);
printf("\n The sorted integer array is as follows\n");
for(k=0;k<size;k++)
printf("%d\t",a[k]);
getch();
}

Binary Trees
This chapter explores one of the most important non-linear data structures, i.e., trees.
Various kinds of trees are available with different features. You will start learning with the most
important tree structure, i.e., the binary tree which is a finite set of elements that is either
empty or further divided into sub-trees.

There are two ways to represent binary trees. These are:

 Using arrays
 Using Linked lists

The Non-Linear Data structure


The data structures that you have learned so far were merely linear - strings, arrays,
lists, stacks, and queues. One of the most important nonlinear data structure is the tree. Trees
are mainly used to represent data containing the hierarchical relationship between elements,
example: records, family trees, and table of contents. A tree may be defined as a finite set 'T' of
one or more nodes such that there is a node designated as the root of the tree and the other
nodes are divided into n>=0 disjoint sets T1, T2, T3, T4 …. Tn are called the subtrees or children
of the root.

What is a Binary Tree?


A binary tree is a special type of tree in which every node or vertex has either no child
node or one child node or two child nodes. A binary tree is an important class of a tree data
structure in which a node can have at most two children.

Child node in a binary tree on the left is termed as 'left child node' and node in the right
is termed as the 'right child node.'

In the figure mentioned below, the root node 8 has two children 3 and 10; then this two
child node again acts as a parent node for 1 and 6 for left parent node 3 and 14 for right parent
node 10. Similarly, 6 and 14 has a child node.

A binary tree may also be defined as follows:

 A binary tree is either an empty tree


 Or a binary tree consists of a node called the root node, a left subtree and a right
subtree, both of which will act as a binary tree once again

Applications of Binary Tree


Binary trees are used to represent a nonlinear data structure. There are various forms of
Binary trees. Binary trees play a vital role in a software application. One of the most important
applications of the Binary tree is in the searching algorithm.

A general tree is defined as a nonempty finite set T of elements called nodes such that:

 The tree contains the root element


 The remaining elements of the tree form an ordered collection of zeros and more
disjoint trees T1, T2, T3, T4 …. Tn which are called subtrees.

Types of Binary Trees are


A full binary tree which is also called as proper binary tree or 2-tree is a tree in which all the
node other than the leaves has exact two children.
A complete binary tree is a binary tree in which at every level, except possibly the last, has to
be filled and all nodes are as far left as possible.

A binary tree can be converted into an extended binary tree by adding new nodes to its
leaf nodes and to the nodes that have only one child. These new nodes are added in such a way
that all the nodes in the resultant tree have either zero or two children. It is also called 2 - tree.

The threaded Binary tree is the tree which is represented using pointers the empty
subtrees are set to NULL, i.e. 'left' pointer of the node whose left child is empty subtree is
normally set to NULL. These large numbers of pointer sets are used in different ways.

Write a C program to implement binary tree traversal oprations

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node
{
int info;
struct node *llink;
struct node *rlink;
};
typedefstruct node *NODE;
NODE insert(intitem,NODE root)
{
if(root==NULL)
{
root=(NODE)malloc(sizeof(struct node));
root->info=item;
root->llink=root->rlink=NULL;
}
else
if(item==root->info)
printf("Duplicate entry\n");
else
if(item<root->info)
root->llink=insert(item,root->llink);
else
root->rlink=insert(item,root->rlink);
return root;
}
void preorder(NODE root)
{
if(root!=NULL)
{
printf("%d\t",root->info);
preorder(root->llink);
preorder(root->rlink);
}
}
voidpostorder(NODE root)
{
if(root!=NULL)
{
postorder(root->llink);
postorder(root->rlink);
printf("%d\t",root->info);
}
}
voidinorder(NODE root)
{
if(root!=NULL)
{
inorder(root->llink);
printf("%d\t",root->info);
inorder(root->rlink);
}
}
void main()
{
NODE root=NULL;
intchoice,item;
clrscr();
printf("Operation on tree traversal\n");
for(;;)
{
printf("\n***MENU***\n");
printf("1.Insert\n2.Preorder\n3.Postorder\n4.Inorder\n5.Quit\n");
printf("Enter your choice\n");
scanf("%d",&choice);
switch(choice)
{
case 1:printf("Enter the item to be inserted\n");
scanf("%d",&item);
root=insert(item,root);
break;
case 2:preorder(root);
break;
case 3:postorder(root);
break;
case 4:inorder(root);
break;
case 5:exit(0);
break;
default:printf("Invlid choice\n");
}
}
}

File Programs Examples

No.1 Write a C program to create a file that contains at least 5 records which
consists of
Book No,Book Name,Author,Publisher,and price.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *ptr;
intbookid,i;
charbookname[20];
char authorname[20];
char publisher[20];
int price;
clrscr();
ptr=fopen("extra16.c","w");
if(ptr==NULL)
{
printf("Error in opening file");
exit(0);
}
for(i=0;i<5;i++)
{
printf("Enter the bookid,bookname,authorname,pulisher,price:\n");
scanf("%d%s%s%s%d",&bookid,&bookname,&authorname,&publisher);
fprintf(ptr,"%d\t%s\t%s\t%s\t%d\n",bookid,bookname,authorname,publisher);
}
fclose(ptr);

getch();
}

Write a C program to count the number of characters in a given file

#include<stdio.h>
void main()
{
FILE *ptr;
char ch;
int count=0;
clrscr();
ptr=fopen("extra10.c","r");
if(ptr==NULL)
{
printf("\nError in opening file");
exit(0);
}
while(!feof(ptr))
{
ch=getc(ptr);
count++;
printf("%c",ch);
}
printf("The number of characters are:%d",count);
fclose(ptr);
getch();
}

Write a C program to display the contents of the file created in program No.1
in the following format
Book_ID Book_Name Book_Author Publisher Price
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *ptr;
int book_id,i;
char book_name[20];
char author_name[20];
char publisher[20];
int price;
clrscr();
ptr=fopen("extra21.c","r");
if(ptr==NULL)
{
printf("Error in file opening");
exit(0);
}
printf("\nBook_ID Book_Name Book_Author Publisher Price\n");
for(i=0;i<=5;i++)
{
fscanf(ptr,"%d\t%s\t%s\t%s\t%d\n",&book_id,&book_name,&author_name,&publisher,&price
);
printf("%d\t%s\t%s\t%s\t%d\n",book_id,book_name,author_name,publisher,price);
}
fclose(ptr);
getch();
}

Write a C program to copy one file to another file using command line
argument
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main(intargc,char *argv[])
{
charch;
inti,n;
FILE *ptr1,*ptr2;
clrscr();
if(argc>0)
{
ptr1=fopen(argv[1],"r");
ptr2=fopen(argv[2],"w");
ch=getc(ptr1);
while(!feof(ptr1))
{
putc(ch,ptr2);
ch=getc(ptr1);
}
}
fclose(ptr1);
fclose(ptr2);
printf("\nThe file is copied\n");
ptr1=fopen(argv[2],"r");
printf("the copied file is\n");
while((ch=getc(ptr2))!=EOF)
printf("%c",ch);
fclose(ptr2);
getch();
}

DFS And BFS Programs


Print all the nodes reachable from a given starting node in a digraph using BFS
method.
#include<stdio.h>
#include<conio.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;
clrscr();
printf("\n enter the number of vertices:\n");
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:\n");
scanf("%d",&v);
bfs(v);
printf("\n The code which are reachable are:");
for(i=1;i<=n;i++)
if(visited[i])
printf("\n %d\t",i);
else
printf("\n BFS is not possible ");
getch();
}
Check whether a given graph is connected or not using DFS method.
#include<stdio.h>
#include<conio.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;
clrscr();
printf("\n enter number of vertices:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
reach[i]=0;
for(i=1;i<=n;i++)
a[i][j]=0;
}
printf("\n enter the adjancency 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");
getch();
}

Thank You
its me Only

Potrebbero piacerti anche