0% found this document useful (0 votes)
6 views25 pages

ds unit 1 new

Data structures are methods for organizing and storing data efficiently, allowing for easier data manipulation. They are classified into linear (e.g., arrays, stacks, queues, linked lists) and non-linear (e.g., trees, graphs) types, each with specific operations and principles. Understanding data structures is crucial for effective data management, performance optimization, and problem-solving in software development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views25 pages

ds unit 1 new

Data structures are methods for organizing and storing data efficiently, allowing for easier data manipulation. They are classified into linear (e.g., arrays, stacks, queues, linked lists) and non-linear (e.g., trees, graphs) types, each with specific operations and principles. Understanding data structures is crucial for effective data management, performance optimization, and problem-solving in software development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

What is Data Structures

Data structure is a method of organizing large amount of data more efficiently so that
any operation on that data becomes easy.
OR
Data Structure is a method of storing and organizing data effectively so that it can be
used efficiently.

Whenever we want to work with large amount of data, then organizing the data is very
important. If the data is not organized effectively, it is very difficult to perform any task
on that data. If the data is organized effectively then any operation can be performed
easily on that data.
Note
 Data structures are used to organize the large amount of data.
 Every data structure follows a particular principle
 Operations on a data structure should not violate the basic principle of that data
structure.
Types of Data Structures

Data structures are classified into 2 types. one is Linear Data Structures and non
linear data structures.
Linear Data Structures
Linear Data Structure is a data structure in which data is organized in sequential order.

Example
1. Arrays
2. Stack
3. Queue
4. Linked List
Non - Linear Data Structures
Non Linear Data Structure is a data structure in which data is organized randomly.

Example
1. Tree
2. Graph

Data Structures UNIT - I


Arrays:
An array is a group of elements of same data type those are stored continuously in
memory and all are called with single name. The elements of the array are
referenced by an index or subscript.
Declaration of creation of array:
syntax:
datatype ArrayName[size];
Example:
int marks[10];

Limitations
 Array size should be fixed.
 Array elements should be same data type.
 Array elements are stored in contiguous memory locations which may not be
always possible.
 Array element Insertion and deletion can be problematic because of shifting of
elements from one location to another location.
Stacks:
Stack is a linear data structure in which insertion and deletion of elements are
done at only one end, which is known as the top of the stack. Stack works on LIFO
(last-in first-out) principle. i.e. the last element which is added to the stack is the
first element which is deleted from the stack. Stacks can be implemented using
arrays or linked lists. Every stack has a variable top associated with it. Top is used
to store the index value of the topmost element of the stack. It is the position
from where the element will be added or deleted. There is another variable SIZE,
which is used to store the size of stack. If top == -1 then the stack is empty and if
top == SIZE–1 then the stack is full. A stack supports three basic operations: push,
pop, and peep. Push operation adds an element to the top of the stack. Pop
operation removes the element from the top of the stack. Peep operation returns
the value of the topmost element of the stack.

Data Structures UNIT - I


Queue:
Queue is a linear data structure in which insertion can be done at rear end and
deletion of elements can be done at front end. Queue works on FIFO principle
(first-in first-out), in which the element that is inserted first is the first one to be
taken out. Queues can be implemented by using either arrays or linked lists. Every
queue has 2 variables front and rear associated with it. Front is the position from
where the element will be added. Rear is the position from where the element
will be deleted. There is another variable SIZE, which is used to store the size of
queue. If front == -1 then the queue is empty and if rear == SIZE–1 then the queue
is full. A queue supports three basic operations: enqueue, dequeue, and peep.
Enqueue operation adds an element at rear. Dequeue operation removes the
element at front. Peep operation returns the value of the front element of the
queue.

Linked Lists:
Linked list is a linear data structure in which elements are called nodes, those are
connected by links. Every node contains the data of the node and a pointer which
stores address of the next node. Every node in the list connects to the next node.
First node of linked list is called Head node. if Head==NULL indicates Linked list is
empty. The operations performed on a linked list include: Insertion: Adding a new
node to the list at a specific position. Deletion: Removing an existing node from
the list at a specific position. Traversal: Accessing each element in linked list.

Trees:
A tree is a non-linear data structure which contains of a group of nodes arranged
in a hierarchical order. First node of tree is called root node. Tree contains of a
root node and left sub tree and right sub-tree. Each node contains a data
element, a left pointer which points to the left sub-tree, and a right pointer
which points to the right sub-tree. If root == NULL then the tree is empty. The
operations performed on a tree include: Insertion: Adding a new node into the
tree. Deletion: Removing an existing node from tree. Traversal: we can display
elements of tree in inorder form or preorder form or postorder form.

Data Structures UNIT - I


Graphs:
A graph is a non-linear data structure which contains a group of vertices (also
called nodes) and edges. A node in the graph may represent a city and the edges
connecting the nodes can represent roads. Graphs do not have any root node.
Every node in the graph can be connected with any node in the graph. Operations
on a graph in data structure include: Add vertex to a graph. Remove vertex from a
graph. Graph traversal means visiting all vertices in a graph in a specific order.

Operations of Data Structures


This section discusses the different operations that can be performed on the various
data structures previously mentioned.
 Inserting : It is used to add new data items to the given list of data items. For
example, to add the details of a new student who has recently joined the course.
 Deleting : It means to remove (delete) a particular data item from the given
collection of data items. For example,
to delete the name of a student who has left the course.
 Traversing : It means to access each data item exactly once so that it can be
processed. For example,
to print the names of all the students in a class.
 Searching : It is used to find the location of one or more data items that satisfy
the given constraint. Such a data item may or may not be present in the given
collection of data items. For example,
to find the names of all the students who secured 100 marks in mathematics.
 Sorting : Data items can be arranged in some order like ascending order or
descending order depending on the type of application. For example, arranging
the names of students in a class in an alphabetical order, or calculating the top
three winners by arranging the participants’ scores in descending order and then
extracting the top three.
 Merging : Lists of two sorted data items can be combined to form a single list of
sorted data items.

Importance of Data Structures (or) Need of Data Structures (or) Advantages of Data
Structures
Linear Data structures are a fundamental concept in computer science and play a crucial
role in many aspects of software development. Here are some of the reasons why linear
data structures are important:
1. Effective storage and retrieval of data:
Data structures allow you to store and retrieve data in an efficient manner. For
example, using a hash table data structure, you can access an element in constant
time, whereas searching for an element in an unordered list would take linear time.

Data Structures UNIT - I


2. Improved performance :
Data structures can help to improve the performance of our code by reducing time
and space complexity of algorithms. For example, using binary search tree instead of
linear search can reduce time takes to find specific element in large dataset.
3. Better problem solving :
Data structures can help to solve complex problems by breaking them into smaller
and manageable parts. For example, Graph data structure can help you solve
problems related to network flow or finding the shortest path between two points.
4. Abstraction :
Data structures provide a way to abstract the underlying complexity of a problem
and simplify it, making it easier to understand and solve.
5. Reusability :
Data structures can be used in many different algorithms and applications, making
them a useful tool in your programming toolbox.

Abstract Data Type

An abstract data type is defined in term of its data items and its
associated operations rather than its implementation.
Or
An abstract data type consists of data as well as the operations to be
performed on the data and implementation will be hidden.

 List ADT, Stacks ADT and queues ADT. The user focuses only about the data and
its operations.
 We can implement Stack ADT and Queue ADT using an array or a linked list.
Advantages of ADT:
1. It helps to develop the program efficiently.
2. Facilitates to break down a complex task into simple subtasks.
3. Helps to reduce the number of things to remember at any time.
4. Simplifies testing and debugging of complex applications.

Data Structures UNIT - I


Time and Space Complexity
The efficiency of an algorithm can be computed by measuring the performance of an
algorithm.
We can measure the performance of an algorithm in two ways.
1. Time Complexity
2. Space Complexity
1. Time Complexity:
 The time complexity of an algorithm is the amount of computing time required to
run an algorithm.
 There are 2 types of computing time
1. Compile time
2. Run time
 The time complexity generally computed at run time (or) execution time.
 The time complexity can be calculated in terms of frequency count.
 Frequency count means number of times the statement should be executed.
 The time complexity can be calculated as
Comments – 0
Assignment / return statement – 1
Conditional (or) Selection Constructs – 1
Example 1 : Sum of the elements in an array.
Statements Step count / Execution Frequency Total Steps
Algorithm Addition(A,N): 0 - -
//A is array name 0 - -
//N is array size 0 - -
sum=0 1 1 1
for i=0 to n-1 do 1 n+1 n+1
sum=sum+A[i] 1 n n
return sum 1 1 1
total time complexity 2n+3

2. Space Complexity:
 Space Complexity can be defined as amount of memory (or) space required by an
Algorithm to run.
 To compute the space complexity we use 2 factors
i. Constant
ii. Instructions.

Data Structures UNIT - I


 The space requirement S(p) = C+Sp
Here C is constant space required for input and output.
Sp is amount of space taken by an instruction or variable or identifiers.

Example 1: Sum of three numbers


Algorithm Add(a,b,c)
{
//a, b, c are float type variables
return a+b+c;
}
 The space required for this algorithm is 3.
 Variables a, b, c requires 3 word size.
 So space complexity is 3.
Example 2: Sum of Array values
Algorithm Addition (A,n)
{
//A is an array of size ‘n’
Sum :=0;
for i:=1 to n do
Sum:=Sum+A[i];
return Sum;
}
 The space required for this algorithm is n+3.
 variables (i, sum, n) requires 3 word size
 Array A requires n word size.
 Space complexity is n+3

What to Analyze in an algorithm?


An Algorithm requires different times to solve a problem as follows
1. Worst case: Maximum amount of time that an algorithm requires to solve a
problem of size ‘n’. Normally we can take upper bound as complexity. We
try to find worst case behavior.
2. Best case: Minimum amount of time that an algorithm requires to solve a
problem of size ‘n’. Normally it is not much useful.
3. Average case: the average amount of time that an algorithm requires to
solve a problem of size ‘n’. Sometimes it is difficult to find. Because we
have to check all possible data organizations

Searching

 Searching means to find whether a particular value is present in an array or not.


 If the value is present in the array, then searching is said to be successful and the
searching process gives the location of that value in the array.
 However, if the value is not present in the array, the searching process displays
an appropriate message and in this case searching is said to be unsuccessful.
 Searching techniques are
a. linear search
b. binary search
c. Fibonacci Search

Data Structures UNIT - I


Linear Searching

 Linear search is a technique which traverses the array sequentially to locate given
item or search element.
 In Linear search, we access each element of an array one by one sequentially and
see whether it is desired element or not. We traverse the entire list and match
each element of the list with the item whose location is to be found. If the match
found then location of the item is returned otherwise the algorithm return NULL.
 A search is successful then it will return the location of desired element
 If A search will unsuccessful if all the elements are accessed and desired element
not found.
 Linear search is mostly used to search an unordered list in which the items are not
sorted.
Algorithm
Step 1 - Read the search element from the user.
Step 2 – Set i=0
Step 3 – Repeat steps 4 to 6 while i<N
Step 4 - Compare the search element with A[i].
Step 5 - If both are matched, then display "Given element is found" and
terminate the function
Step 6 - If both are not matched, then set i=i+1.
Step 7 – If i==N then display "Element is not found" and terminate the function.
Example:
Given list of elements are 10, 50, 30, 20, 5, 12 and Search element is 5.

Step 1:
Compare search element (5) with first element (10)

Both are not matching. So move to next element.


Step 2:
Compare search element (5) with next element (50)

Both are not matching. So move to next element.


Step 3:
Compare search element (5) with next element (30)

Both are not matching. So move to next element.

Data Structures UNIT - I


Step 4:
Compare search element (5) with next element (20)

Both are not matching. So move to next element.


Step 5:
Compare search element (5) with next element (5)

Both are matching. So display element found at index 4.


Time Complexity: time complexity of linear search is O(n), where n is the size of
the input array. The worst-case scenario is when the search element is not
present in the array, and the function has to go through the entire array to find
that search element.
Space Complexity: space complexity of linear search is O(1), the function uses only
a constant amount of space to store variables. The amount of space used does
not depend on the size of the input array.
C Program to perform Linear Search
#include<stdio.h>
void main()
{
int a[100],n,i,sno;
printf("Enter size: ");
scanf("%d",&n);
printf("Enter %d element: ",n);
for( i=0;i<n;i++ )
scanf("%d",&a[i]);
printf("Enter search element: ");
scanf("%d",&sno);
for( i=0;i<n;i++ )
{
if( sno==a[i])
break;
}
if( i==n )
printf("%d is not found\n",sno);
else
printf("Found at position %d\n",i);
}
Binary Search
 Binary search is the search technique which works efficiently on the sorted lists.
Hence, in order to search an element into some list by using binary search
technique, we must ensure that the list is sorted.

Data Structures UNIT - I


 Binary search follows divide and conquer approach in which, the list is divided
into two halves and the item is compared with the middle element of the list. If
the match is found then, the location of middle element is returned otherwise,
we search into either of the halves depending upon the result produced through
the match.

Algorithm:
Step 1 - Read the search element from the user.
Step 2 – Set First=0, Last=N-1
Step 3 – Repeat Step 4 to while First<=Last
Step 4 - Find mid=(First+Last)/2.
Step 5 - Compare the search element with the middle element.
Step 6 - If both are matched, then display "Given element is found" and terminate
the function.
Step 7 - If the search element is smaller than middle element then set Last=mid-1
and goto Step 3.
Step 8 - If the search element is greater than middle element then set
First=mid+1 and goto Step 3.
Step 9 - If First>Last then display "Element is not found in the list" and terminate
the function.
Example 1: Given list of elements are 10,12,20,32,50,55,65,80,99 and search
element is 12.

Step 1: let F=0, L=n-1 and find middle = (F+L)/2


Compare search element (12) with middle element (50)

Search element(12) is smaller than middle element(50). So, we need


to search only in left sub list i.e. (10, 12, 20, 32).
set L=M-1
Step 2:
Compare search element (12) with middle element (12)

Search element(12) and middle element(12) are matching.


So, the result is “Element found at index 1”
Example 2: Given list of elements are 10,12,20,32,50,55,65,80,99 and search
element is 80.

Data Structures UNIT - I


Step 1:
Compare search element (80) with middle element (50)

search element(80) is larger than Middle element(50). So, we


need to search only in right sub list i.e. (55, 65, 80, 99).
set F=M+1
Find M=(F+L)/2
Step 2:
Compare search element (80) with middle element (65)

search element(80) is larger than Middle element(65). So, we need


to search only in right sub list i.e. (80, 99).
set F=M+1
Find M=(F+L)/2
Step 3:
Compare search element (80) with middle element (80)

Middle element(80) and search element(80) are matching.


So, the result is “Element found at index 7”.
Time Complexity: time complexity of binary search is O(log n) – Binary search
algorithm divides the input array in half at every step, reducing the search
space by half, and hence has a time complexity of logarithmic order.
Space Complexity: space complexity of Binary search is O(1). It requires only
constant space for storing the first, last, and mid values. So its space
complexity is O(1).
C Program to perform Binary Search
#include<stdio.h>
void main()
{
int a[100],n,i,sno,F,L,M;
printf("size: ");
scanf("%d",&n);
printf("elements: ");
for( i=0;i<n;i++ )
scanf("%d",&a[i]);
printf("search element: ");
scanf("%d",&sno);
F=0;
L=n-1;

Data Structures UNIT - I


while( F<=L )
{
M=(F+L)/2;
if( sno>a[M] )
F=M+1;
else if( sno<a[M])
L=M-1;
else
{
printf("found at %d\n",M+1);
break;
}
}
if(F>L)
printf("not found\n");
}

Sorting

Sorting is a technique to rearrange the list of records (elements) either in ascending or


descending order. Sorting is performed according to some key value of each record.
Types of sorting :
1. Selection Sort
2. Bubble Sort
3. Insertion Sort
4. Merge Sort
5. Quick Sort
6. Heap Sort
7. Radix Sort
Selection Sort

 From given a list of elements, first we find first smallest element and swap it with
first element. Then we find second smallest element and swap it with second
element. These steps are then repeated until we sort all the elements.
Algorithm :
SELECTION SORT(ARR, N)
Step 1: Repeat Steps 2 and 3 for I = 0 to N-1
Step 2: find the position[POSN] of smallest element.
Step 3: SWAP ARR[I] with ARR[POSN]
Step 4: EXIT
Example :

Data Structures UNIT - I


Time Complexity:
Number of elements in an array is ‘N’
Number of passes required to sort is ‘N-1’
Number of comparisons in each pass is 1st pass N-1, 2nd Pass N-2 …
Time required for complete sorting is:
Data Structures UNIT - I
T(n) <= (N-1) *(N-1)
T(n) <= (N-1)2
Finally, The time complexity is O(n2).

Best-case: O(n2), best case occurs when the array is already sorted. (where n is
the number of integers in an array)
Average-case: O(n2), the average case arises when the elements of the array are
in a disordered or random order, without a clear ascending or descending
pattern.
Worst-case: O(n2), The worst-case scenario arises when we need to sort an array
in ascending order, but the array is initially in descending order.
C Program to perform Selection Sort
#include<stdio.h>
void main()
{
int a[100],n,i,j,t,posn;
printf("Enter no of elements: ");
scanf("%d",&n);
printf("Enter the elements: ");
for( i=0;i<n;i++ )
scanf("%d",&a[i]);
printf("Array before sort: ");
for( i=0;i<n;i++ )
printf("%d ",a[i]);
printf("\n");
for( i=0;i<n;i++ )
{
posn=i;
for( j=i+1;j<n;j++)
{
if( a[j] < a[posn] )
posn=j;
}
t=a[i];
a[i]=a[posn];
a[posn]=t;
}
printf("Array after sort: ");
for( i=0;i<n;i++ )
printf("%d ",a[i]);
printf("\n");
}

Bubble Sort

Bubble Sort is also called as Exchange Sort


 In Bubble Sort, each element is compared with its adjacent element
 If the last element is smaller than the second last element then the position of
the elements are interchanged.
 Otherwise, the position of the elements is not changed.
 The same procedure is repeated until no more elements are left for comparison.

Data Structures UNIT - I


 After the 1st pass the largest element is placed at (N-1)th location.
 Given a list of n elements, the bubble sort requires up to n – 1 passes.
 Ex: asked to sort a list (10, 5, 2, 15, 12, 7) on paper.
Example :
Given array is

First Pass
Compare 13 and 32.

13 and 32 are already sorted. Now compare 32 and 26.

32 is greater than 26. So, swap 32 and 26. Now array is

Now compare 32 and 35.

32 and 35 are already sorted. Now compare 35 and 10

35 is greater than 10. So, swap 35 and 10. Now array is

Second Pass
Compare 13 and 26.

13 and 26 are already sorted. Now compare 26 and 32

26 and 32 are already sorted. Now compare 32 and 10

Data Structures UNIT - I


32 is greater than 10. So, swap 32 and 10. Now array is

Third Pass
compare 13 and 26.

13 and 26 are already sorted. Now compare 26 and 10.

26 is greater than 10. So, swap 26 and 10, Now array is

Fourth Pass
Compare 13 and 10

13 is greater than 10. So, swap 13 and 10. Now array is

Algorithm :
BUBBLE SORT(ARR, N)
Step 1: Read the array elements
Step 2: i:=0;
Step 3: Repeat step 4 and step 5 until i<n
Step 4: j:=N-1;
Step 5: Repeat step 6 until j>=i
Step 6: if A[j] > A[j-1]
Swap(A[j],A[j+1])
End if
End loop 5
End loop 3
Step 7: EXIT
Best Case Time Complexity: O(N)
The best case occurs when the array is already sorted. So the number of comparisons
required is N-1 and the number of swaps required = 0. Hence the best case complexity
is O(N).
Worst Case Time Complexity: O(N2)
The worst-case condition for bubble sort occurs when elements of the array are
arranged in decreasing order. In the worst case, the total number of iterations or passes
required to sort a given array is (N-1). Here ‘N’ is the number of elements present in the
array. Hence the worst case time complexity is O(N2)

Data Structures UNIT - I


Average Case Time Complexity: O(N2)
The number of comparisons is constant in Bubble Sort. So in average case, there are
O(N2) comparisons. This is because irrespective of the arrangement of elements, the
number of comparisons C(N) is same.
C Program to perform Bubble Sort
#include<stdio.h>
void main()
{
int a[100],n,i,j,t;
printf("n: ");
scanf("%d",&n);
printf("Elements: ");
for( i=0;i<n;i++ )
scanf("%d",&a[i]);
printf("Before sorting: ");
for( i=0;i<n;i++ )
printf("%d ",a[i]);
printf("\n");
for( i=n-1;i>=0;i-- )
{
for( j=0;j<i;j++)
{
if( a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
printf("After sorting: ");
for( i=0;i<n;i++ )
printf("%d ",a[i]);
printf("\n");
}
Insertion Sort
 In Insertion sort the list can be divided into two parts, one is sorted list and other is
unsorted list.
 In each pass the first element of unsorted list is transfers to sorted list by inserting it
in appropriate position or proper place.
 The similarity can be understood from the style we arrange a deck of cards. This sort
works on the principle of inserting an element at a particular position, hence the
name Insertion Sort.
Algorithm
Step 1: We start with second element of the given array. Consider first element
already in sorting.
Step 2: We compare the key element with the element(s) before it, in this case,
element at index 0:

Data Structures UNIT - I


o If the key element is less than the first element, we insert the key element
before the first element.
o If the key element is greater than the first element, then we insert it after
the first element.
Step 3: Then, we make the third element of the array as key and will compare it
with elements to it's left and insert it at the proper position. And we go on
repeating this, until the array is sorted.

Time Complexity of Insertion Sort


 The worst-case time complexity of the Insertion sort is O(N2)
 The average case time complexity of the Insertion sort is O(N2)
 The time complexity of the best case is O(N).

C Program to perform Insertion Sort


#include<stdio.h>
void main()
{
int a[100],n,i,j,t,key;
printf("Enter no of elements: ");
scanf("%d",&n);
printf("Enter the elements: ");
for( i=0;i<n;i++ )
scanf("%d",&a[i]);
printf("Array before sort: ");
for( i=0;i<n;i++ )
printf("%d ",a[i]);
printf("\n");
for( i=1;i<n;i++ )
{
Data Structures UNIT - I
key=a[i];
for( j=i-1;j>=0;j--)
{
if( a[j]>key)
a[j+1]=a[j];
else
break;
}
a[j+1]=key;
}
printf("Array after insertion sort: ");
for( i=0;i<n;i++ )
printf("%d ",a[i]);
printf("\n");
}
QUICK SORT

Quick Sort uses divide and conquer technique. Quick sort is a highly
efficient sorting algorithm and is based on partitioning an array into smaller sub
arrays. A large array is partitioned into two half arrays. First array holds smaller than
the pivot. Second array holds higher than pivot.
Quick sort partitions an array and then calls itself recursively twice to sort the two
resulting sub arrays. This algorithm is quite efficient for large-sized data sets as its
average and worst case complexity are of Ο(n2), where n is the number of items.

Data Structures UNIT - I


Algorithm
Step 1 − Choose the lowest index value has pivot
Step 2 − Take two variables to point left and right of the list excluding pivot
Step 3 − left points to the low index+1
Step 4 − right points to the high
Step 5 − while value at left is less than pivot move right
Step 6 − while value at right is greater than pivot move left
Step 7 − if both step 5 and step 6 does not match swap left and right
Step 8 − if left ≥ right, the point where they met is new pivot

Program
#include<stdio.h>

void quicksort( int a[100],int lb,int ub)


{
int left,right,key,t;
key=a[lb];
left=lb+1;
right=ub;
if( lb<ub )
{
while( left<=right )
{
while( a[left]<key )
left++;
while( a[right]> key )
right--;
if( left<right )
{
t=a[left];
a[left]=a[right];
a[right]=t;
}
}

Data Structures UNIT - I


t=a[lb];
a[lb]=a[right];
a[right]=t;
quicksort( a,lb,right-1);
quicksort(a,right+1,ub);
}
}
void main()
{
int a[100],n,i;
printf("enter array size");
scanf("%d",&n);
printf("\nenter %d elements",n);
for( i=0;i<n;i++)
scanf("%d",&a[i]);
quicksort(a,0,n-1);
printf("\narray after sort\n");
for( i=0;i<n;i++)
printf("%5d",a[i]);
}

MERGE SORT

Merge sort is a sorting technique based on divide and conquer technique. With
the worst-case time complexity being Ο(n log n), it is one of the most respected
algorithms.

Data Structures UNIT - I


Algorithm
MergeSort(arr[], left, right)
If left < right
Step 1. Find the middle point to divide the array into two halves:
mid = (left+right)/2
Step 2. Call mergeSort for first half:
Call mergeSort(arr, left, mid)
Step 3. Call mergeSort for second half:
Call mergeSort(arr, mid+1, right)
Step 4. Merge the two halves sorted in step 2 and 3:
Call merge(arr, left, mid, right)
Program
#include<stdio.h>
int a[10], b[10];
void merge(int First, int mid, int Last)
{
int i=0, j=mid+1, k=0;
while( i <= mid && j <= Last )
{
if(a[i] <= a[j])
b[k] = a[i++];
else
b[k] = a[j++];
k++;
}
while(i <= mid)
b[k++] = a[i++];
while(j <= Last)
b[k++] = a[j++];
for(k= 0; k <= Last; k++)
a[k] = b[k];
}
void sort(int First, int Last)
{
int mid;
if(First < Last)
{
mid = (First + Last) / 2;
sort(First, mid);
sort(mid+1, Last);
merge(First, mid, Last);
}
else
return;
}
int main()
{
int n,i;
printf("Enter array size : ");
scanf("%d",&n);

Data Structures UNIT - I


printf("Enter %d elements : ",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("List before sorting\n");
for(i = 0; i < n; i++)
printf("%d ", a[i]);
sort(0, n-1);
printf("\nList after sorting\n");
for(i = 0; i <n; i++)
printf("%d ", a[i]);
}
Array as an Abstract Data Type

An array is a variable which can store multiple values of same data type.

 The Array as ADT


 An array is a set of pairs (index, value).
 Index is associated with a value

Operations of Array
Following operations can be performed on arrays:
1. Insertion
2. Deletion
3. Traversing
4. Searching
5. Sorting
Insertion
Insertion is a process of inserting one or more elements into an array. Based on the
requirement, a new element can be added at the beginning, end, or any given position.

INSERT( A,N,P,ITEM )
// This algorithm inserts an element into the Array.
// A is name of array.
// N is size of array
// P is position where to be inserted.
// ITEM is the value to be inserted.
Step1: set J=N
Step2: Repeat Step 3 and 4 while J>=P
Step3: A[J]=A[J-1];
Step4: J=J-1
Step5: A[P]=ITEM
Step6: N=N+1

Data Structures UNIT - I


DELETION
Deletion is a process of removing an existing element from the an array.

DELETE( A,N,P)
// This algorithm deletes an element from the Array.
// A is name of array.
// N is size of array
// P is the position of element to be deleted.
Step1: set J=P
Step2: Repeat Step 3 and 4 while J<N
Step3: A[J-1]=A[J];
Step4: J=J+1
Step5: N=N-1

Traverse
It is a process of displaying all elements of array.

DISPLAY( A,N )
// This algorithm displays all element of Array.
// A is name of array.
// N is size of array
Step1: set I=0
Step2: Repeat Step 3 and 4 while I<N
Step3: write( A[I] )
Step4: I=I+1

Searching
It is a process of checking whether an element is present in array or not.

SEARCH( A,N,ITEM )
// This algorithm searches an element of Array.
// A is an array name.
// N is the array Size
// ITEM is the element to be searched.
Step1: set I=0
Step2: Repeat Step 3 and 4 while I<N
Step3: if A[I]==ITEM then
write( ITEM is found at I position )
break
Step4: I=I+1
Step5: if I==N then
write( ITEM not found )

Data Structures UNIT - I


Sorting
It is a process of arranging elements of array in ascending or descending.

Sorting( A,N)
 This algorithm arranges all elements of Array in
order.
 A is an array name.
 N is the array Size
Step1: set I=0
Step2: Repeat Step 3 to 7 while I<N
Step3: Set J=I+1
Step4: Repeat Step 5 to 6 while J<N
Step5: If A[I] > A[J] then
Swap A[I] and A[J]
Step6: J=J+1
Step7: I=I+1

Data Structures UNIT - I

You might also like