0% found this document useful (0 votes)
10 views43 pages

Data Structures1

This document provides an introduction to linear data structures, defining data structures as organized collections of data and detailing primitive and non-primitive types. It explains linear data structures such as arrays, stacks, queues, and linked lists, along with operations like traversing, searching, inserting, and deleting. Additionally, it covers abstract data types, time and space complexity, and searching algorithms including linear and binary search.
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)
10 views43 pages

Data Structures1

This document provides an introduction to linear data structures, defining data structures as organized collections of data and detailing primitive and non-primitive types. It explains linear data structures such as arrays, stacks, queues, and linked lists, along with operations like traversing, searching, inserting, and deleting. Additionally, it covers abstract data types, time and space complexity, and searching algorithms including linear and binary search.
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/ 43

UNIT I

INTRODUCTION TO LINEAR DATA STRUCUTRE

1.1. DATA STRUCTURES:

Data may be organized in many different ways logical or mathematical model of a program
particularly organization of data. This organized data is called “Data Structure”.
Or
The organized collection of data is called a ‘Data Structure’.

Data Structure=Organized data +Allowed operations


Data Structure involves two complementary goals. The first goal is to identify and develop useful,
mathematical entities and operations and to determine what class of problems can be solved by
using these entities and operations. The second goal is to determine representation for those
abstract entities to implement abstract operations on this concrete representation.
Primitive Data structures are directly supported by the language ie; any operation is directly
performed in these data items.
Ex: integer, Character, Real numbers etc.
Non-primitive data types are not defined by the programming language, but are instead created
by the programmer. Linear data structures organize their data elements in a linear fashion, where
data elements are attached one after the other. Linear data structures are very easy to implement,
since the memory of the computer is also organized in a linear fashion. Some commonly used
linear data structures are arrays, linked lists, stacks and queues.
In nonlinear data structures, data elements are not organized in a sequential fashion. Data
structures like multidimensional arrays, trees, graphs, tables and sets are some examples of widely
used nonlinear data structures.
Operations on the Data Structures:
Following operations can be performed on the data structures:
1. Traversing- It is used to access each data item exactly once so that it can be processed.
2. Searching- It is used to find out the location of the data item if it exists in the given collection
of data items.
3. Inserting- It is used to add a new data item in the given collection of data items.
4. Deleting- It is used to delete an existing data item from the given collection of data items.
Linear Data Structure
A linear data structure is a structure in which the elements are stored sequentially, and the
elements are connected to the previous and the next element. As the elements are stored
sequentially, so they can be traversed or accessed in a single run. The implementation of linear
data structures is easier as the elements are sequentially organized in memory. The data
elements in an array are traversed one after another and can access only one element at a time.
The types of linear data structures are Array, Queue, Stack, Linked List.Array is a type of data
structure that stores data elements in adjacent locations. Array is considered as linear data
structure that stores elements of same data types.
STACK:
Stack is a linear data structure in which the insertion and deletion operations are performed at only
one end. In a stack, adding and removing of elements
are performed at a single position which is known as
"top".
QUEUE:
Queue is a linear data structure in which the insertion and deletion operations are performed at two different
ends.

LINKED LIST:
A linked list is a way to store a collection of elements. Each element in a linked list is stored in
the form of a node. A data part stores the element and a next part stores the link to the next node.

ARRAY:
An array is a linear data structure that collects elements of the same data type and stores them in
contiguous and adjacent memory locations.

1.2. ABSTRACT DATA TYPE MODEL:


An Abstract Data Type (ADT) is a programming concept that defines a high-level view of a data
structure, without specifying the implementation details. In other words, it is a blueprint for creating
a data structure that defines the behavior and interface of the structure, without specifying how it is
implemented.
ABSTRACT DATA TYPES:

1. List ADT

Views of list

• The data is generally stored in key sequence in a list which has a head structure
consisting of count, pointers and address of compare function needed to compare the
data in the list.
• The data node contains the pointer to a data structure and a self-referential
pointer which points to the next node in the list.

2. Stack ADT
View of stack

In Stack ADT Implementation instead of data being stored in each node, the
pointer to data is stored.
The program allocates memory for the data and address is passed to the stack
ADT.
The head node and the data nodes are encapsulated in the ADT. The calling
function can only see the pointer to the stack.
The stack head structure also contains a pointer to top and count of number of
entries currently in stack.

.
3. Queue ADT

View of Queue
The queue abstract data type (ADT) follows the basic design of the stack abstract data
type.
Each node contains a void pointer to the data and the link pointer to the next
element in the queue. The program’s responsibility is to allocate memory for
storing the data.
.
1.3. OVERVIEW OF TIME AND SPACE COMPLEXITY :

Analyzing an algorithm means determining the amount of resources (such as time and
memory) needed to execute it. Algorithms are generally designed to work with an arbitrary
number of inputs, so the efficiency or complexity of an algorithm is stated in terms of time
and space complexity.
The time complexity of an algorithm is basically the running time of a program as a function
of the input size. Similarly, the space complexity of an algorithm is the amount of computer
memory that is required during the program execution as a function of the input size.
In other words, the number of machine instructions which a program executes is called its
time complexity. This number is primarily dependent on the size of the program’s input and
the algorithm used.

Time Complexity:
The amount of time required for an algorithm to complete its execution is its time complexity.
An algorithm is said to be efficient if it takes the minimum (reasonable) amount of time to
complete its execution.
The number of steps any problem statement is assigned depends on the kind of statement.
For example, comments 0 steps.

1. We introduce a variable, count into the program statement to increment count with initial
value 0.Statement to increment count by the appropriate amount are introduced into the
program.
This is done so that each time a statement in the original program is executes count is incremented
by the step count of that statement.
Algorithm:
Algorithm sum(a,n)
{
s= 0.0;
count = count+1;
for I=1 to n do 8
{
count =count+1;
s=s+a[I];
count=count+1;
}
count=count+1;
count=count+1;
return s;
}
If the count is zero to start with, then it will be 2n+3 on termination. So each invocation of
sum execute a total of 2n+3 steps.
2. The second method to determine the step count of an algorithm is to build a table in which
we list the total number of steps contributes by each statement.
First determine the number of steps per execution (s/e) of the statement and the total number
of times (ie., frequency) each statement is executed.
By combining these two quantities, the total contribution of all statements, the step count for the
entire algorithm is obtained.
Statement S/e Frequency Total
1. Algorithm 0 - 0
Sum(a,n) 0 - 0
2.{ 1 1 1
3. S=0.0; 1 n+1 n+1
4. for I=1 to n do 1 n n
5. s=s+a[I]; 1 1 1
6. return s; 0 - 0
7. }
Total 2n+3

Space Complexity:
The amount of space occupied by an algorithm is known as Space Complexity. An algorithm
is said to be efficient if it occupies less space and required the minimum amount of time to
complete its execution.

Fixed part:
It varies from problem to problem. It includes the space needed for storing instructions,
constants, variables, and structured variables (like arrays and structures ).
Variable part:
It varies from program to program. It includes the space needed for recursion stack, and
for structured variables that are allocated space dynamically during the runtime of a program.

The space requirement s(p) of any algorithm p may therefore be written as,
S(P) = c+ Sp(Instance characteristics)
Where ‘c’ is a constant.

1.4. Searching:
Searching is a process of finding a particular record, which can be a single
element or a small chunk, within a huge amount of data. The data can be in various
forms: arrays, linked lists, trees, heaps, and graphs etc. With the increasing amount
of data nowadays, there are multiple techniques to perform the searching
operation.is a process of finding a particular record, which can be a single element
or a small chunk, within a huge amount of data. The data can be in various forms:
arrays, linked lists, trees, heaps, and graphs etc. With the increasing amount of data
nowadays, there are multiple techniques to perform the searching operation.

1.4.1. Linear search

Linear search is a type of sequential searching algorithm. In this method, every


element within the input array is traversed and compared with the key element to
be found. If a match is found in the array the search is said to be successful; if there
is no match found the search is said to be unsuccessful and gives the worst- case
time complexity.

For instance, in the given animated diagram, we are searching for an element 33.
Therefore, the linear search method searches for it sequentially from the very first
element until it finds a match. This returns a successful search.

In the same diagram, if we have to search for an element 46, then it returns an
unsuccessful search since 46 is not present in the input.

Algorithm: LINEAR(DATA, N,ITEM, LOC)


Here DATA is a linear Array with N elements. And ITEM is a given item of information. This
algorithm finds the location LOC of an ITEM in DATA. LOC=-1 if the search is unsuccessful.
Step 1: Set DATA[N+1]=ITEM
Step 2: Set LOC=1
Step 3: Repeat while (DATA [LOC] != ITEM)
Set LOC=LOC+1
Step 4: if LOC=N+1 then
Set LOC= -1.
Step 5: Exit

Pseudocode
procedure linear_search (list, value)

for each item in the list

if match item == value

return the item's location

end if

end for

end procedure

Analysis
Linear search traverses through every element sequentially therefore, the best case
is when the element is found in the very first iteration. The best-case time
complexity would be O(1).

However, the worst case of the linear search method would be an unsuccessful
search that does not find the key value in the array, it performs n iterations.
Therefore, the worst-case time complexity of the linear search algorithm would be
O(n).

Example

Let us look at the step-by-step searching of the key element (say 47) in an array
using the linear search method.
Step 1 : The linear search starts from the 0th index. Compare the key element
with the value in the 0th index, 34.

However, 47 ≠ 34. So it moves to the next element.

Step 2 : Now, the key is compared with value in the 1st index of the array.

Still, 47 ≠ 10, making the algorithm move for another iteration.

Step 3 : The next element 66 is compared with 47. They are both not a match so
the algorithm compares the further elements.

Step 4 : Now the element in 3rd index, 27, is compared with the key value, 47.
They are not equal so the algorithm is pushed forward to check the next element.

Step 5 : Comparing the element in the 4th index of the array, 47, to the key 47. It is
figured that both the elements match. Now, the position in which 47 is present, i.e.,
4 is returned.

The output achieved is “Element found at 4th index”.

Implementation
The Linear Search program can be seen implemented in four programming
languages. The function compares the elements of input with the key value and
returns the position of the key in the array or an unsuccessful search prompt if the
key is not present in the array.

Program for Linear Search:

#include <stdio.h>

void linear_search(int a[], int n, int key){

int i, count = 0;
for(i = 0; i < n; i++) {

if(a[i] == key) { // compares each element of the array

printf("The element is found at %d position\n", i+1);

count = count + 1;

if(count == 0) // for unsuccessful search

printf("The element is not present in the array\n");

int main(){

int i, n, key;

n = 6;

int a[10] = {12, 44, 32, 18, 4, 10};

key = 18;

linear_search(a, n, key);

key = 23;

linear_search(a, n, key);

return 0;

Output:

The element is found at 4 position

The element is not present in the array

1.4.2. BINARY SEARCH:

Binary search is a fast search algorithm with run-time complexity of Ο(log n).
This search algorithm works on the principle of divide and conquer, since it
divides the array into half before searching. For this algorithm to work properly,
the data collection should be in the sorted form.

Binary search looks for a particular key value by comparing the middle most item
of the collection. If a match occurs, then the index of item is returned. But if the
middle item has a value greater than the key value, the right sub-array of the middle
item is searched. Otherwise, the left sub-array is searched. This process continues
recursively until the size of a subarray reduces to zero.

Ex: consider a list of sorted elements stored in an Array A is

Let the key element which is to be searched is 35.


Key=35
The number of elements in the list n=9.
Step 1: MID= [lb+ub]/2
=(1+9)/2
=5

Key<A[MID]
i.e. 35<46.
So search continues at lower half of the array.
Ub=MID-1
=5-1 = 4.
Step 2: MID= [lb+ub]/2
=(1+4)/2
=2.

Key>A[MID]
i.e. 35>12.
So search continues at Upper Half of the array.
Lb=MID+1
=2+1
= 3. 50
Step 3: MID= [lb+ub]/2
=(3+4)/2
=3.

Key>A[MID]
i.e. 35>30.
So search continues at Upper Half of the array.
Lb=MID+1
=3+1
= 4.

Step 4: MID= [lb+ub]/2


=(4+4)/2
=4.

ALGORITHM:
BINARY SEARCH[A,N,KEY]
Step 1: begin
Step 2: [Initilization]
Lb=1; ub=n;
Step 3: [Search for the ITEM]
Repeat through step 4,while Lower bound is less than Upper Bound.
Step 4: [Obtain the index of middle value]
MID=(lb+ub)/2
Step 5: [Compare to search for ITEM]
If Key<A[MID] then
Ub=MID-1
Other wise if Key >A[MID] then
Lb=MID+1
Otherwise write “Match Found”
Return Middle.
Step 6: [Unsuccessful Search]
write “Match Not Found”
Step 7: Stop.

Implementation:

Binary search is a fast search algorithm with run-time complexity of Ο(log n). This
search algorithm works on the principle of divide and conquer. For this algorithm
to work properly, the data collection should be in a sorted form.

Program for binary search:

#include<stdio.h>

void binary_search(int a[], int low, int high, int key){

int mid;

mid = (low + high) / 2;

if (low <= high) {

if (a[mid] == key)

printf("Element found at index: %d\n", mid);

else if(key < a[mid])

binary_search(a, low, mid-1, key);

else if (a[mid] < key)

binary_search(a, mid+1, high, key);

} else if (low > high)

printf("Unsuccessful Search\n");

int main(){

int i, n, low, high, key;

n = 5;

low = 0;
high = n-1;

int a[10] = {12, 14, 18, 22, 39};

key = 22;

binary_search(a, low, high, key);

key = 23;

binary_search(a, low, high, key);

return 0;

Output
Element found at index: 3
Unsuccessful Search

Advantages: When the number of elements in the list is large, Binary Search executed faster
than linear search. Hence this method is efficient when number of elements is large.

Disadvantages: To implement Binary Search method the elements in the list must be in sorted
order, otherwise it fails.

1.5. SORTING
INTRODUCTION
Sorting is a technique of organizing the data. It is a process of arranging the records, either in
ascending or descending order i.e. bringing some order lines in the data. Sort methods are very
important in Data structures.
Sorting can be performed on any one or combination of one or more attributes present in each
record. It is very easy and efficient to perform searching, if data is stored in sorting order. The
sorting is performed according to the key value of each record. Depending up on the makeup of
key, records can be stored either numerically or alphanumerically. In numerical sorting, the
records arranged in ascending or descending order according to the numeric value of the key.

1.5.1. BUBBLE SORT


Bubble Sort: This sorting technique is also known as exchange sort, which arranges values by
iterating over the list several times and in each iteration the larger value gets bubble up to the end
of the list. This algorithm uses multiple passes and in each pass the first and second data items
are compared. if the first data item is bigger than the second, then the two items are swapped.
Next the items in second and third position are compared and if the first one is larger
than the second, then they are swapped, otherwise no change in their order. This process
continues for each successive pair of data items until all items are sorted.
Bubble Sort Algorithm:
Step 1: Repeat Steps 2 and 3 for i=1 to 10
Step 2: Set j=1
Step 3: Repeat while j<=n
if a[i] < a[j] Then
interchange a[i] and a[j]
[End of if]
Set j = j+1
[End of Inner Loop]
[End of Step 1 Outer Loop]
Step 4: Exit

Example1:
Example 2:
To discuss bubble sort in detail, let us consider an arrayA[]that has the
followingelements:
A[] = {30, 52, 29, 87, 63, 27, 19, 54}
Pass 1:
Compare 30 and 52. Since 30 < 52, no swapping is done.
Compare 52 and 29. Since 52 > 29, swapping is
done. 30, 29, 52, 87, 63, 27, 19, 54
Compare 52 and 87. Since 52 < 87, no swapping is done.
Compare 87 and 63. Since 87 > 63, swapping is
done. 30, 29, 52, 63, 87, 27, 19, 54
Compare 87 and 27. Since 87 > 27, swapping is
done. 30, 29, 52, 63, 27, 87, 19, 54
Compare 87 and 19. Since 87 > 19, swapping is
done. 30, 29, 52, 63, 27, 19, 87, 54
Compare 87 and 54. Since 87 > 54, swapping is
done. 30, 29, 52, 63, 27, 19, 54, 87
Observe that after the end of the first pass, the largest element is placed at the
highest index of the array. All the other elements are still unsorted.
Pass 2:
Compare 30 and 29. Since 30 > 29, swapping is
done. 29, 30, 52, 63, 27, 19, 54, 87
Compare 30 and 52. Since 30 < 52, no swapping is done.
Compare 52 and 63. Since 52 < 63, no swapping is done.
Compare 63 and 27. Since 63 > 27, swapping is
done. 29, 30, 52, 27, 63, 19, 54, 87
Compare 63 and 19. Since 63 > 19, swapping is done.
29, 30, 52, 27, 19, 63, 54, 87
Compare 63 and 54. Since 63 > 54, swapping
is done. 29, 30, 52, 27, 19, 54, 63, 87
Observe that after the end of the second pass, the second largest element is
placed at the second highest index of the array. All the other elements are still
unsorted.
Pass 3:
Compare 29 and 30. Since 29 < 30, no swapping is done.
Compare 30 and 52. Since 30 < 52, no swapping is done.
Compare 52 and 27. Since 52 > 27, swapping
is done. 29, 30, 27, 52, 19, 54, 63, 87
Compare 52 and 19. Since 52 > 19, swapping
is done. 29, 30, 27, 19, 52, 54, 63, 87
Compare 52 and 54. Since 52 < 54, no swapping is done.
Observe that after the end of the third pass, the third largest element is placed at
the third highest index of the array. All the other elements are still unsorted.
Pass 4:
Compare 29 and 30. Since 29 < 30, no swapping is done.
Compare 30 and 27. Since 30 > 27, swapping
is done. 29, 27, 30, 19, 52, 54, 63, 87
Compare 30 and 19. Since 30 > 19, swapping
is done. 29, 27, 19, 30, 52, 54, 63, 87
Compare 30 and 52. Since 30 < 52, no swapping is done.
Observe that after the end of the fourth pass, the fourth largest element is placed at
the fourth highest index of the array. All the other elements are still unsorted.
Pass 5:
Compare 29 and 27. Since 29 > 27, swapping
is done. 27, 29, 19, 30, 52, 54, 63, 87
Compare 29 and 19. Since 29 > 19, swapping
is done. 27, 19, 29, 30, 52, 54, 63, 87
Compare 29 and 30. Since 29 < 30, no swapping is done.
Observe that after the end of the fifth pass, the fifth largest element is placed at
the fifth highest index of the array. All the other elements are still unsorted.
Pass 6:
Compare 27 and 19. Since 27 > 19, swapping
is done. 19, 27, 29, 30, 52, 54, 63, 87
Compare 27 and 29. Since 27 < 29, no swapping is done.
Observe that after the end of the sixth pass, the sixth largest element is placed at
the sixth largest index of the array. All the other elements are still unsorted.
Pass 7:
(a) Compare 19 and 27. Since 19 < 27, no swapping is done.
Observe that the entire list is sorted now.

Advantages :
Simple and easy to implement
In this sort, elements are swapped in place without using additional temporary
storage, so the space requirement is at a minimum.
Disadvantages :
It is slowest method . O(n2)
Inefficient for large sorting lists.

Program
#include<stdio.h>
void main ()
{
int i, j,temp;
int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
for(i = 0; i<10; i++)
{
for(j = i+1; j<10; j++)
{
if(a[j] > a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("Printing Sorted Element List ...\n");
for(i = 0; i<10; i++)
{
printf("%d\n",a[i]);
}
}
Output:
Printing Sorted Element List . . .
7
9
10
12
23
34
34
44
78
101
1.5.2. SELECTION SORT
In selection sort, the smallest value among the unsorted elements of the array is selected in every
pass and inserted to its appropriate position into the array. First, find the smallest element of the
array and place it on the first position. Then, find the second smallest element of the array and
place it on the second position. The process continues until we get the sorted array. The array
with n elements is sorted by using n-1 pass of selection sort algorithm.
Algorithm for selection sort
SELECTION SORT(ARR, N)
Step 1: Repeat Steps 2 and 3 for K = 1 to N-1
Step 2: CALL SMALLEST(ARR, K, N, POS)
Step 3: SWAP A[K] with ARR[POS]
[END OF LOOP]
Step 4: EXIT
SMALLEST (ARR, K, N, POS)
Step 1: [INITIALIZE] SET SMALL = ARR[K]
Step 2: [INITIALIZE] SET POS = K
Step 3: Repeat for J = K+1 to N
IF SMALL > ARR[J]
SET SMALL = ARR[J]
SET POS = J
[END OF IF]
[END OF LOOP]
Step 4: RETURN POS
Example 1: 3, 6, 1, 8, 4, 5

Example2 :
Example: Consider the following array with 6 elements. Sort the elements of the array by using
selection sort.
A = {10, 2, 3, 90, 43, 56}.

Pass A[0] A[1] A[2] A[3] A[4] A[5]


1 2 10 3 90 43 56
2 2 3 10 90 43 56
3 2 3 10 90 43 56
4 2 3 10 43 90 56
5 2 3 10 43 56 90

Sorted A = {2, 3, 10, 43, 56, 90}

Advantages:
It is simple and easy to implement.
It can be used for small data sets.
It is 60 per cent more efficient than bubble sort.
Disadvantages:
Running time of Selection sort algorithm is very poor of 0 (n2).
However, in case of large data sets, the efficiency of selection sort drops as
compared to insertion sort.
Program
#include<stdio.h>
int smallest(int[],int,int);
void main ()
{
int a[10] = {10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
int i,j,k,pos,temp;
for(i=0;i<10;i++)
{
pos = smallest(a,10,i);
temp = a[i];
a[i]=a[pos];
a[pos] = temp;
}
printf("\nprinting sorted elements...\n");
for(i=0;i<10;i++)
{
printf("%d\n",a[i]);
}
}
int smallest(int a[], int n, int i)
{
int small,pos,j;
small = a[i];
pos = i;
for(j=i+1;j<10;j++)
{
if(a[j]<small)
{
small = a[j];
pos=j;
}
}
return pos;
}
Output:
printing sorted elements...
7
9
10
12
23
23
34
44
78
101
INSERTION SORT
Insertion sort is one of the best sorting techniques. It is twice as fast as Bubble sort. In Insertion
sort the elements comparisons are as less as compared to bubble sort. In this comparison the value
until all prior elements are less than the compared values is not found. This means that all the
previous values are lesser than compared value. Insertion sort is good choice for small values and
for nearly sorted values.
Working of Insertion sort:
The Insertion sort algorithm selects each element and inserts it at its proper position in a sub list
sorted earlier. In a first pass the elements A1 is compared with A0 and if A[1] and A[0] are not
sorted they are swapped.
In the second pass the element[2] is compared with A[0] and A[1]. And it is inserted at its proper
position in the sorted sub list containing the elements A[0] and A[1]. Similarly doing i th iteration
the element A[i] is placed at its proper position in the sorted sub list, containing the elements
A[0],A[1],A[2], ............................. A[i-1].
To understand the insertion sort consider the unsorted Array A={7,33,20,11,6}.
Algorithm for insertion sort
INSERTION-SORT (ARR, N)
Step 1: Repeat Steps 2 to 5 for K = 1 to N – 1
Step 2: SET TEMP = ARR[K]
Step 3: SET J = K - 1
Step 4: Repeat while TEMP <= ARR[J]
SET ARR[J + 1] = ARR[J]
SET J = J - 1
[END OF INNER LOOP]
Step 5: SET ARR[J + 1] = TEMP
[END OF LOOP]
Step 6: EXIT
Example 1:
Consider an array of integers given below. We will sort the values in the
Array using insertion sort
23 15 29 11 1
Example2:
The steps to sort the values stored in the array in ascending order using Insertion sort are given
below:
7 33 20 11 6

Step 1: The first value i.e; 7 is trivially sorted by itself.


Step 2: the second value 33 is compared with the first value 7. Since 33 is greater than 7, so no
changes are made.
Step 3: Next the third element 20 is compared with its previous element (towards left).Here 20
is less than 33.but 20 is greater than 7. So it is inserted at second position. For this 33 is shifted
towards right and 20 is placed at its appropriate position.
7 33 20 11 6

7 20 33 11 6

Step 4: Then the fourth element 11 is compared with its previous elements. Since 11 is less than
33 and 20 ; and greater than 7. So it is placed in between 7 and 20. For this the elements 20 and
33 are shifted one position towards the right.
7 20 33 11 6

7 11 20 33 6

Step5: Finally the last element 6 is compared with all the elements preceding it. Since it is smaller
than all other elements, so they are shifted one position towards right and 6 is inserted at the first
position in the array. After this pass, the Array is sorted.
7 11 20 33 6

6 7 11 20 33
Step 6: Finally the sorted Array is as follows:
6 7 11 20 33

Advantages of Insertion Sort:


• It is simple sorting algorithm, in which the elements are sorted by considering one item
at a time. The implementation is simple.
• It is efficient for smaller data set and for data set that has been substantially sorted
before.
• It does not change the relative order of elements with equal keys
• It reduces unnecessary travels through the array
• It requires constant amount of extra memory space.

Disadvantages:-
• It is less efficient on list containing more number of elements.
• As the number of elements increases the performance of program would be slow .
UNIT II
LINKED LISTS
1.1. Linked lists
A linked list is a way to store a collection of elements. Each element in a linked list is stored in
the form of a node. A data part stores the element and a next part stores the link to the next node.

Linked List:

Advantages of linked lists:


Linked lists have many advantages. Some of the very important advantages are:
1. Linked lists are dynamic data structures. i.e., they can grow or shrink during the execution of
a program.
2. Linked lists have efficient memory utilization.
3. Insertion and Deletions are easier and efficient. Linked lists provide flexibility in inserting a
data item at a specified position and deletion of the data item from the given position.
4. Many complex applications can be easily carried out with linked lists.
Disadvantages of linked lists:
1. It consumes more space because every node requires a additional pointer to store address of
the next node.
2. Searching a particular element in list is difficult and also time consuming.
Types of Linked list:
• Single linked list
• double linked list
• circular linked list
• double circular linked lists

Single linked list:


Single linked list is a sequence of elements in which every element has link to its next element in
the sequence.
In any single linked list, the individual element is called as "Node". Every "Node" contains two
fields, data and next. The data field is used to store actual value of that node and next field is
used to store the address of the next node in the sequence.

Operations on single linked list:


In a single linked list we perform the following operations...
1. Creation
2. Insertion
3. Deletion
4. Traverse
5. Searching
Creation of a node:
Step 1: Include all the header files and user defined functions.
Step 2: Define a Node structure with two members data and next
Step 3: Define a Node pointer 'head' and set it to NULL.
Step 4: Implement the main method by displaying operations menu

struct node
{
int data;
struct node *next;
};

Insertion:
In a single linked list, the insertion operation can be performed in three ways. They are as
follows...
1. Inserting At Beginning of the list
2. Inserting At End of the list
3. Inserting At Specific location in the list

Inserting At Beginning of the list


Step 1: Start
Step 2: Create a newnode with given value.
Step 3: Check whether list is Empty (head == NULL)
Step 4: If it is Empty:
set newNode→next = NULL
set head = newNode.
Step 5: If it is Not Empty:
set newNode→next = head
set head = newNode.
Step 6: Stop

Inserting At End of the list


Step 1: Start
Step 2: Create a newnode with given value.
Step 3: Check whether list is Empty (head == NULL)
Step 4: If it is Empty:
set newNode→next = NULL
set head = newNode.
Step 5: If it is Not Empty then define a node pointer temp
temp = head (initialize temp with head).
Step 6: move temp to its next node until it reaches to the last node in the list
(until temp → next = NULL).
Step 7: Set temp → next = newNode.
Step 8: Stop

Inserting At Specific location in the list (After a Node)


Step 1: Start
Step 2: Create a newnode with given value.
Step 3: Check whether list is Empty (head == NULL)
Step 4: If it is Empty:
set newNode→next = NULL
set head = newNode.
Step 5: If it is Not Empty, then define a node pointer temp
temp = head (initialize temp with head).
Step 6: move temp to its next node until it reaches specific location to insert
(until temp → data = location).
Step 7: Set newNode → next = temp → next
Set temp → next = newNode
Step 8: Stop
Deletion:In a single linked list, the deletion operation can be performed in three ways. They are
as follows...
1. Deleting from Beginning of the list
2. Deleting from End of the list
3. Deleting a Specific Node

Deleting from Beginning of the list


Step 1: Start
Step 2: Check whether list is Empty (head == NULL)
Step 3: If it is Empty:
display 'List is Empty!!! Deletion is not possible'.
Step 4: If it is Not Empty then define a Node pointer 'temp'
Set temp = head (initialize temp with head).
Step 5: Set head = temp → next
delete temp.
free (temp)

Deleting from End of the list


Step 1: start
Step 2: Check whether list is Empty (head == NULL)
Step 3: If it is Empty:
display 'List is Empty!!! Deletion is not possible'
Step 4: If it is Not Empty then define two Node pointers 'temp1' and 'temp2'
Set temp1 = head (initialize 'temp1' with head).
Step 5: set 'temp2 = temp1 ' and move temp1 to its next node.
Step 6: Repeat the same until it reaches to the last node in the list.
(until temp1 → next == NULL)
Step 7: Finally, Set temp2 → next = NULL
delete temp1.
free (temp1).

Deleting a Specific Node from the list


Step 1: start
Step 2: Check whether list is Empty (head == NULL)
Step 3: If it is Empty:
display 'List is Empty!!! Deletion is not possible'
Step 4: If it is Not Empty, then define two Node pointers 'temp1' and 'temp2'
Set temp1 = head (initialize 'temp1' with head).
Step 5: set 'temp2 = temp1 ' and move temp1 to its next node.
Step 6: Repeat the same until it reaches specific node which we want to delete.
Step 7: set temp2 → next = temp1 → next
delete temp1
free(temp1)
Traverse
Step 1: Start
Step 2: Check whether list is Empty (head == NULL)
Step 3: If it is Empty:
display List is Empty!!!
Step 4: If it is Not Empty, then define a Node pointer 'temp'
Set temp = head (initialize temp with head).
Step 5: Keep displaying temp-->
temp = temp-->next
Step 6: Stop
Searching
Step 1: Start
Step 2: Check whether list is Empty (head == NULL)
Step 3: If it is Empty:
display List is Empty. Searching is not possible.
Step 4: If it is Not Empty: define a Node pointer 'temp'
Set temp = head (initialize temp with head).
Step 5: Enter item to search i.e., key
Step 6: move temp until it reaches key.
temp = temp →next
Step 7: if(temp →data = key) then
print “search is successful”
else
print “search is unsuccessful”
1.8 Double linked list:
In double linked list, every node has link to its previous node and next node. So, we can traverse
forward by using next field and can traverse backward by using previous field. Every node in a
double linked list contains three fields and they are shown in the following figure...
• In double linked list, the first node must be always pointed by head.
• Always the previous field of the first node must be NULL.
• Always the next field of the last node must be NULL.
In a Double linked list we perform the following operations...
1. Creation
2. Insertion
3. Deletion
4. Traverse
5. Searching

Creation of a node:
Step 1: Include all the header files and user defined functions.
Step 2: Define a Node structure with two members data and next
Step 3: Define a Node pointer 'head' and set it to NULL
Step 4: Implement the main method by displaying operations menu

struct node
{
int data;
struct node *prev, *next;
};
Insertion
In a double linked list, the insertion operation can be performed in three ways as follows...
1. Inserting At Beginning of the list
2. Inserting At End of the list
3. Inserting At Specific location in the list

Inserting At Beginning of the list


Step 1: Start
Step 2: Create a newNode with given value
Step 3: Check whether list is Empty (head == NULL)
Step 4: If it is Empty then
Set newnode→prev =null
Set newNode → next = null
Set newnode→data = value
Set head = newnode
Step 5: If it is not Empty then
Set newNode → next = head
Set head→prev = newNode
Set head = newnode
Inserting At Specific location in the list
Step 1: Start
Step 2: Create a newNode with given value
Step 3: Check whether list is Empty (head == NULL)
Step 4: If it is Empty then
Set newnode→prev =null
Set newNode → next = null
Set newnode→data = value
Set head = newnode
Step 5: If it is not Empty: (define a node pointer temp)
Set temp = head (initialize temp with head)
Step 6: move temp to its next node until it reaches specific location to insert
(until temp → data = location).
Step 7: Set newnode→next = temp→next
Set newnode→prev=temp
Set (temp→next)→prev = newnode
Set temp →next = newnode
Inserting At End of the list
Step 1: Start
Step 2: Create a newNode with given value
Step 3: Check whether list is Empty (head == NULL)
Step 4: If it is Empty then
Set newnode→prev =null
Set newNode → next = null
Set newnode→data = value
Set head = newnode
Step 5: If it is not Empty: (define a node pointer temp)
Set temp = head (initialize temp with head)
Step 6: move temp to its next node until it reaches last node to insert.
(until temp →next = null)
Step 7: Set temp-->ext = newnode
Set newnode→rev = temp
Set newnode →next =null
Deletion:
In a double linked list, the deletion operation can be performed in three ways as follows...
1. Deleting from Beginning of the list
2. Deleting from End of the list
3. Deleting at Specific location

Deleting from Beginning of the list


Step 1: Check whether list is Empty (head == NULL)
Step 2: If it is Empty then
display 'List is Empty!!! Deletion is not possible'.
Step 3: If it is not Empty: then define a Node pointer 'temp'
Set temp = head (initialize temp with head).
Step 4: Set head = temp→next
Set head→prev = null
Set temp →next = null
delete temp
free (temp)
Deleting at Specific location
Step 1: Check whether list is Empty (head == NULL)
Step 2: If it is Empty then
display 'List is Empty!!! Deletion is not possible'.
Step 3: If it is not Empty, then define a Node pointer 'temp'
Set temp =head (initialize temp with head).
Step 4: Keep moving the temp until it reaches specific node to delete.
Step 5: Set (temp→prev)→next = temp→next
Set (temp→next)→prev = temp→prev
delete temp
free(temp)
Deleting from End of the list
Step 1: Check whether list is Empty (head == NULL)
Step 2: If it is Empty then
display 'List is Empty!!! Deletion is not possible'.
Step 3: If it is not Empty, then define a Node pointer 'temp'
Set temp =head (initialize temp with head).
Step 4: Keep moving the temp until it reaches last node to delete.
(until temp → next = NULL)
Step 5: set (temp → prev) → next = null
delete temp
free(temp)
Traverse (forward):
Step 1: Start
Step 2: Check whether list is Empty (head == NULL)
Step 3: If it is Empty:
display List is Empty!!!
Step 4: If it is Not Empty, then define a Node pointer 'temp'
Set temp = head (initialize temp with head).
Step 5: Keep moving temp forward
temp = temp→next
Step 6: Keep displaying temp→data until temp reaches last node
(until temp→next=null)
Step 6: Stop
Traverse (backward):
Step 1: Start
Step 2: Check whether list is Empty (head == NULL)
Step 3: If it is Empty:
display List is Empty!!!
Step 4: If it is Not Empty, then define a Node pointer 'temp'
Set temp = tail (initialize temp with tail).
Step 5: Keep moving temp backward
temp = temp→prev
Step 6: Keep displaying temp→data until temp reaches head node
(until temp→prev=null)
Step 7: Stop
Searching:
Step 1: Start
Step 2: Check whether list is Empty (head == NULL)
Step 3: If it is Empty:
display “List is Empty. Searching is not possible”.
Step 4: If it is Not Empty then define a Node pointer 'temp'
Set temp = head (initialize temp with head).
Step 5: Enter item to search i.e., key
Step 6: move temp until it reaches key.
temp = temp →next
Step 7: if(temp →data = key) then
print “search is successful”
else
print “search is unsuccessful”
1.9 Circular linked list:
Circular linked list is a sequence of elements in which every element has link to its next element
in the sequence and the last element has a link to the first element in the sequence.

Operations:
• Insertion
• Deletion
• Traverse
• Searching

Insertion (begin)
Step 1: Start
Step 2: Create a new node with a given value
Step 3: Check whether list is Empty (head == NULL)
Step 4: If list is empty then
Set Newnode→data = value
Set Newnode→next=newnode
Set head = newnode
Set tail = newnode
Step 5: If list is non-empty then
Set newnode→next=head
Set head=newnode
Set tail→next=newnode
Step 6: Stop
Insertion (End)
Step 1: Start
Step 2: Create a new node with a given value
Step 3: Check whether list is Empty (head == NULL)
Step 4: If list is empty:
Set Newnode→data = value
Set Newnode→next=newnode
Set head = newnode
Set tail = newnode
Step 5: If list is non-empty:
Set tail→next=newnode
Set tail=newnode
Set tail→next=head
Step 6: Stop
Insertion (Specific location)
Step 1: Start
Step 2: Create a new node with a given value
Step 3: Check whether list is Empty (head == NULL)
Step 4: If list is empty:
Set Newnode→data = value
Set Newnode→next=newnode
Set head = newnode
Set tail = newnode
Step 5: If list is not empty: Define pointer temp.
Set temp = head (initialize temp with head)
Step 6: move temp to its next node until it reaches the location to insert new node
Set temp=temp→next
Set temp→data=location
Step 7: when location is reached
Set newnode→next=temp→next
Set temp→next=newnode
Step 8: Stop
Deletion (begin)
Step 1: Start
Step 2: Check whether list is Empty (head == NULL)
Step 3: If it is Empty:
Display “List is Empty. Deletion is not possible”
Step 4: If it is Not Empty: Define pointer temp.
Set temp = head (initialize temp with head)
Step 5: Set head=temp-->ext
Set tail→next=head
Step 6: Delete temp
free (temp)
Step 7: Stop
Deletion (end)
Step 1: Start
Step 2: Check whether list is Empty (head == NULL)
Step 3: If it is Empty:
Display “List is Empty. Deletion is not possible”
Step 4: If it is Not Empty: define pointers 'temp1' and 'temp2'
temp1 = head (initialize temp1 with head).
Step 5: set temp2 = temp1 and move temp1 to its next node
Step 6: Repeat the same until temp1 → next == head
Step 7: set temp2→next=head
Step 8: delete temp1
free (temp1)
Deletion (specific location)
Step 1: Start
Step 2: Check whether list is Empty (head == NULL)
Step 3: If it is Empty:
Display “List is Empty. Deletion is not possible”
Step 4: If it is Not Empty: define pointers 'temp1' and 'temp2'
temp1 = head (initialize temp1 with head).
Step 5: set temp2 = temp1 and move temp1 to its next node
Step 6: Repeat the same until temp1 reaches the node to delete at specific position in the list
Step 7: Set temp2→next = temp1→next
Step 8: delete temp1
free (temp1)
Step 9: stop.
1.10 .Circular Double linked list:
Circular Doubly Linked List has properties of both doubly linked list and circular linked list in
which two consecutive elements are linked or connected by previous and next pointer and the last
node points to first node by next pointer and also the first node points to last node by previous
pointer.

Difference between Arrays and Linked List?

Arrays Linked List


1. Arrays are used in the predictable storage 1. Linked List are used in the unpredictable
requirement ie; exert amount of data storage storage requirement ie; exert amount of data
required by the program can be determined. storage required by the program can’t be
2. In arrays the operations such as insertion determined.
and deletion are done in an inefficient manner. 2. In Linked List the operations such as
3. The insertion and deletion are done by insertion and deletion are done more efficient
moving the elements either up or down. manner ie; only by changing the pointer.
4. Successive elements occupy adjacent space 3. The insertion and deletion are done by only
on memory. changing the pointers.
5. In arrays each location contain DATA only 4. Successive elements need not occupy
6. The linear relation ship between the data adjacent space.
elements of an array is reflected by the physical 5. In linked list each location contains data and
relation ship of data in the memory. pointer to denote whether the next element
7. In array declaration a block of memory present in the memory.
space is required. 6. The linear relation ship between the data
8. There is no need of storage of pointer or lines elements of a Linked List is reflected by the
9. The Conceptual view of an Array is as Linked field of the node.
follows: 7. In Linked list there is no need of such
thing.
8. In Linked list a pointer is stored along into
the element.
9. The Conceptual view of Linked list is as
follows:

10.In array there is no need for an element to


specify whether the next is stored

10. There is need for an element (node) to


specify whether the next node is formed.

Applications of linked lists:


1. Sparse matrix Representation
2. Polynomial representation
3. Dynamic storage management
Polynomial Representation
Array implementation:

Linked list implementation:


Procedure
Procedure to add polynomials using linked list

You might also like