[go: up one dir, main page]

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

DSA unit 1

The document provides an overview of data and data structures, explaining their importance in organizing and managing data efficiently in computer science. It classifies data structures into primitive and non-primitive types, detailing linear structures like arrays and linked lists, as well as non-linear structures like trees and graphs. Additionally, it discusses the key features, objectives, and basic operations associated with data structures, emphasizing their role in improving program performance and solving complex problems.

Uploaded by

Sarkar Khan
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)
26 views25 pages

DSA unit 1

The document provides an overview of data and data structures, explaining their importance in organizing and managing data efficiently in computer science. It classifies data structures into primitive and non-primitive types, detailing linear structures like arrays and linked lists, as well as non-linear structures like trees and graphs. Additionally, it discusses the key features, objectives, and basic operations associated with data structures, emphasizing their role in improving program performance and solving complex problems.

Uploaded by

Sarkar Khan
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

Data is a collection of facts and figures or a set of values or values of a specific format that

refers to a single set of item values. The data items are then classified into sub-items,
which is the group of items that are not known as the simple primary form of the item.
Let us consider an example where an employee name can be broken down into three
sub-items: First, Middle, and Last. However, an ID assigned to an employee will generally
be considered a single item.

In the example mentioned above, the items such as ID, Age, Gender, First, Middle, Last,
Street, Locality, etc., are elementary data items. In contrast, the Name and the Address are
group data items.

What is Data Structure?


Data Structure is a branch of Computer Science. The study of data structure allows us to
understand the organization of data and the management of the data flow in order to
increase the efficiency of any process or program. Data Structure is a particular way of
storing and organizing data in the memory of the computer so that these data can easily
be retrieved and efficiently utilized in the future when required. The data can be managed
in various ways, like the logical or mathematical model for a specific organization of data is
known as a data structure.
The scope of a particular data model depends on two factors:
1. First, it must be loaded enough into the structure to reflect the definite correlation of the
data with a real-world object.
2. Second, the formation should be so straightforward that one can adapt to process the data
efficiently whenever necessary.

Some examples of Data Structures are Arrays, Linked Lists, Stack, Queue, Trees, etc. Data
Structures are widely used in almost every aspect of Computer Science, i.e., Compiler
Design, Operating Systems, Graphics, Artificial Intelligence, and many more.
Data Structures are the main part of many Computer Science Algorithms as they allow the
programmers to manage the data in an effective way. It plays a crucial role in improving
the performance of a program or software, as the main objective of the software is to
store and retrieve the user's data as fast as possible.
Understanding the Need for Data Structures
As applications are becoming more complex and the amount of data is increasing every
day, which may lead to problems with data searching, processing speed, multiple
requests handling, and many more. Data Structures support different methods to organize,
manage, and store data efficiently. With the help of Data Structures, we can easily
traverse the data items. Data Structures provide Efficiency, Reusability, and Abstraction.

Why should we learn Data Structures?


1. Data Structures and Algorithms are two of the key aspects of Computer Science.
2. Data Structures allow us to organize and store data, whereas Algorithms allow us to
process that data meaningfully.
3. Learning Data Structures and Algorithms will help us become better Programmers.
4. We will be able to write code that is more effective and reliable.
5. We will also be able to solve problems more quickly and efficiently.

Understanding the Objectives of Data Structures


Data Structures satisfy two complementary objectives:
1. Correctness: Data Structures are designed to operate correctly for all kinds of inputs based
on the domain of interest. In order words, correctness forms the primary objective of Data
Structure, which always depends upon the problems that the Data Structure is meant to
solve.
2. Efficiency: Data Structures also requires to be efficient. It should process the data quickly
without utilizing many computer resources like memory space. In a real-time state, the
efficiency of a data structure is a key factor in determining the success and failure of the
process.

Understanding some Key Features of Data Structures


Some of the Significant Features of Data Structures are:
1. Robustness: Generally, all computer programmers aim to produce software that yields
correct output for every possible input, along with efficient execution on all hardware
platforms. This type of robust software must manage both valid and invalid inputs.
2. Adaptability: Building software applications like Web Browsers, Word Processors, and
Internet Search Engine include huge software systems that require correct and efficient
working or execution for many years. Moreover, software evolves due to emerging
technologies or ever-changing market conditions.
3. Reusability: The features like Reusability and Adaptability go hand in hand. It is known that
the programmer needs many resources to build any software, making it a costly enterprise.
However, if the software is developed in a reusable and adaptable way, then it can be
applied in most future applications. Thus, by executing quality data structures, it is possible
to build reusable software, which appears to be cost-effective and timesaving.
Classification of Data Structures
A Data Structure delivers a structured set of variables related to each other in various ways. It
forms the basis of a programming tool that signifies the relationship between the data elements
and allows programmers to process the data efficiently.

We can classify Data Structures into two categories:

1. Primitive Data Structure


2. Non-Primitive Data Structure

The following figure shows the different classifications of Data Structures.

Primitive Data Structures


1. Primitive Data Structures are the data structures consisting of the numbers and the
characters that come in-built into programs.
2. These data structures can be manipulated or operated directly by machine-level
instructions.
3. Basic data types like Integer, Float, Character, and Boolean come under the
Primitive Data Structures.
4. These data types are also called Simple data types, as they contain characters that
can't be divided further

Non-Primitive Data Structures


1. Non-Primitive Data Structures are those data structures derived from Primitive
Data Structures.
2. These data structures can't be manipulated or operated directly by machine-level
instructions.
3. The focus of these data structures is on forming a set of data elements that is
either homogeneous (same data type) or heterogeneous (different data types).
4. Based on the structure and arrangement of data, we can divide these data
structures into two sub-categories -

. Linear Data Structures


a. Non-Linear Data Structures

Linear Data Structures


A data structure that preserves a linear connection among its data elements is known as a
Linear Data Structure. The arrangement of the data is done linearly, where each element
consists of the successors and predecessors except the first and the last data element.
However, it is not necessarily true in the case of memory, as the arrangement may not be
sequential.

Based on memory allocation, the Linear Data Structures are further classified into two
types:

1. Static Data Structures: The data structures having a fixed size are known as Static
Data Structures. The memory for these data structures is allocated at the compiler
time, and their size cannot be changed by the user after being compiled; however,
the data stored in them can be altered.
The Array is the best example of the Static Data Structure as they have a fixed size,
and its data can be modified later.
2. Dynamic Data Structures: The data structures having a dynamic size are known as
Dynamic Data Structures. The memory of these data structures is allocated at the
run time, and their size varies during the run time of the code. Moreover, the user
can change the size as well as the data elements stored in these data structures at
the run time of the code.
Linked Lists, Stacks, and Queues are common examples of dynamic data structures

Types of Linear Data Structures


1. Arrays

An Array is a data structure used to collect multiple data elements of the same data type
into one variable. Instead of storing multiple values of the same data types in separate
variable names, we could store all of them together into one variable. This statement
doesn't imply that we will have to unite all the values of the same data type in any
program into one array of that data type. But there will often be times when some specific
variables of the same data types are all related to one another in a way appropriate for an
array.

An Array is a list of elements where each element has a unique place in the list. The data
elements of the array share the same variable name; however, each carries a different
index number called a subscript. We can access any data element from the list with the
help of its location in the list. Thus, the key feature of the arrays to understand is that the
data is stored in contiguous memory locations, making it possible for the users to traverse
through the data elements of the array using their respective indexes.

Figure 3. An Array

Arrays can be classified into different types:

1. One-Dimensional Array: An Array with only one row of data elements is known as
a One-Dimensional Array. It is stored in ascending storage location.
2. Two-Dimensional Array: An Array consisting of multiple rows and columns of data
elements is called a Two-Dimensional Array. It is also known as a Matrix.
3. Multidimensional Array: We can define Multidimensional Array as an Array of
Arrays. Multidimensional Arrays are not bounded to two indices or two dimensions
as they can include as many indices are per the need.

2. Linked Lists

A Linked List is another example of a linear data structure used to store a collection of data
elements dynamically. Data elements in this data structure are represented by the Nodes
connected using links or pointers. Each node contains two fields, the information field
consists of the actual data, and the pointer field consists of the address of the subsequent
nodes in the list. The pointer of the last node of the linked list consists of a null pointer, as it
points to nothing. Unlike the Arrays, the user can dynamically adjust the size of a Linked
List as per the requirements.
Figure 4 A Linked Lists

Linked Lists can be classified into different types:

● Singly Linked List: A Singly Linked List is the most common type of Linked List. Each
node has data and a pointer field containing an address to the next node.
● Doubly Linked List: A Doubly Linked List consists of an information field and two
pointer fields. The information field contains the data. The first pointer field contains
an address of the previous node, whereas another pointer field contains a
reference to the next node. Thus, we can go in both directions (backward as well as
forward).
● Circular Linked List: The Circular Linked List is similar to the Singly Linked List. The
only key difference is that the last node contains the address of the first node,
forming a circular loop in the Circular Linked List.

3. Stacks

A Stack is a Linear Data Structure that follows the LIFO (Last In, First Out) principle that allows
operations like insertion and deletion from one end of the Stack, i.e., Top. Stacks can be
implemented with the help of contiguous memory, an Array, and non-contiguous memory, a
Linked List. Real-life examples of Stacks are piles of books, a deck of cards, piles of money, and
many more.
The above figure represents the real-life example of a Stack where the operations are
performed from one end only, like the insertion and removal of new books from the top of
the Stack. It implies that the insertion and deletion in the Stack can be done only from the
top of the Stack. We can access only the Stack's tops at any given time.

The primary operations in the Stack are as follows:

● Push: Operation to insert a new element in the Stack is termed as Push


Operation.
● Pop: Operation to remove or delete elements from the Stack is termed as Pop
Operation.

4. Queues
A Queue is a linear data structure similar to a Stack with some limitations on the
insertion and deletion of the elements. The insertion of an element in a Queue is
done at one end, and the removal is done at another or opposite end. Thus, we
can conclude that the Queue data structure follows FIFO (First In, First Out)
principle to manipulate the data elements. Implementation of Queues can be
done using Arrays, Linked Lists, or Stacks. Some real-life examples of Queues
are a line at the ticket counter, an escalator, a car wash, and many more.
The above image is a real-life illustration of a movie ticket counter that can help us
understand the Queue where the customer who comes first is always served first. The
customer arriving last will undoubtedly be served last. Both ends of the Queue are open
and can execute different operations. Another example is a food court line where the
customer is inserted from the rear end while the customer is removed at the front end
after providing the service they asked for.

The following are the primary operations of the Queue:

● Enqueue: The insertion or Addition of some data elements to the Queue is called
Enqueue. The element insertion is always done with the help of the rear pointer.
● Dequeue: Deleting or removing data elements from the Queue is termed Dequeue.
The deletion of the element is always done with the help of the front pointer.

Types of Non-Linear Data Structures


The following is the list of Non-Linear Data Structures that we generally use:
1. Trees
A Tree is a Non-Linear Data Structure and a hierarchy containing a collection of nodes
such that each node of the tree stores a value and a list of references to other nodes (the
"children").
The Tree data structure is a specialized method to arrange and collect data in the
computer to be utilized more effectively. It contains a central node, structural nodes, and
sub-nodes connected via edges. We can also say that the tree data structure consists of
roots, branches, and leaves connected.

Trees can be classified into different types:


a) Binary Tree: A Tree data structure where each parent node can have at most two
children is termed a Binary Tree.
b) Binary Search Tree: A Binary Search Tree is a Tree data structure where we can
easily maintain a sorted list of numbers.
c) AVL Tree: An AVL Tree is a self-balancing Binary Search Tree where each node
maintains extra information known as a Balance Factor whose value is either -1, 0,
or +1.
d) B-Tree: A B-Tree is a special type of self-balancing Binary Search Tree where each
node consists of multiple keys and can have more than two children.

2. Graphs
A Graph is another example of a Non-Linear Data Structure comprising a finite
number of nodes or vertices and the edges connecting them. The Graphs are
utilized to address problems of the real world in which it denotes the problem area
as a network such as social networks, circuit networks, and telephone networks.
For instance, the nodes or vertices of a Graph can represent a single user in a
telephone network, while the edges represent the link between them via telephone.
The Graph data structure, G is considered a mathematical structure comprised of a
set of vertices, V and a set of edges, E as shown below:
G = (V,E)

Basic Operations of Data Structures


In the following section, we will discuss the different types of operations that we can
perform to manipulate data in every data structure:
1. Traversal: Traversing a data structure means accessing each data element exactly once so
it can be administered. For example, traversing is required while printing the names of all
the employees in a department.
2. Search: Search is another data structure operation which means to find the location of one
or more data elements that meet certain constraints. Such a data element may or may not
be present in the given set of data elements. For example, we can use the search operation
to find the names of all the employees who have the experience of more than 5 years.
3. Insertion: Insertion means inserting or adding new data elements to the collection. For
example, we can use the insertion operation to add the details of a new employee the
company has recently hired.
4. Deletion: Deletion means to remove or delete a specific data element from the given list of
data elements. For example, we can use the deleting operation to delete the name of an
employee who has left the job.
5. Sorting: Sorting means to arrange the data elements in either Ascending or Descending
order depending on the type of application. For example, we can use the sorting operation
to arrange the names of employees in a department in alphabetical order or estimate the
top three performers of the month by arranging the performance of the employees in
descending order and extracting the details of the top three.
6. Merge: Merge means to combine data elements of two sorted lists in order to form a single
list of sorted data elements.
7. Create: Create is an operation used to reserve memory for the data elements of the
program. We can perform this operation using a declaration statement. The creation of
data structure can take place either during the following:

. Compile-time
a. Run-time
For example, the malloc() function is used in C Language to create data structure.
2. Selection: Selection means selecting a particular data from the available data. We can
select any particular data by specifying conditions inside the loop.
3. Update: The Update operation allows us to update or modify the data in the data structure.
We can also update any particular data by specifying some conditions inside the loop, like
the Selection operation.
4. Splitting: The Splitting operation allows us to divide data into various subparts decreasing
the overall process completion time.

The following are some applications of Data Structures:

1. Data Structures help in the organization of data in a computer's memory.


2. Data Structures also help in representing the information in databases.
3. Data Structures allows the implementation of algorithms to search through data
(For example, search engine).
4. We can use the Data Structures to implement the algorithms to manipulate data
(For example, word processors).
5. We can also implement the algorithms to analyse data using Data Structures (For
example, data miners).
6. Data Structures support algorithms to generate the data (For example, a random
number generator).
7. Data Structures also support algorithms to compress and decompress the data (For
example, a zip utility).
8. We can also use Data Structures to implement algorithms to encrypt and decrypt
the data (For example, a security system).
9. With the help of Data Structures, we can build software that can manage files and
directories (For example, a file manager).
10. We can also develop software that can render graphics using Data Structures. (For
example, a web browser or 3D rendering software).

What is abstract data type?


An abstract data type is an abstraction of a data structure that provides only the interface
to which the data structure must adhere (follow). The interface does not give any specific
details about something should be implemented or in what programming language.

In other words, we can say that abstract data types are the entities that are definitions of data and
operations but do not have implementation details. In this case, we know the data that we are
storing and the operations that can be performed on the data, but we don't know about the
implementation details. The reason for not having implementation details is that every
programming language has a different implementation strategy for example; a C data structure is
implemented using structures while a C++ data structure is implemented using objects and classes.

For example, a List is an abstract data type that is implemented using a dynamic array and
linked list. A queue is implemented using linked list-based queue, array-based queue. A
Map is implemented using Tree map, hash map, or hash table.

Abstract data type model


Before knowing about the abstract data type model, we should know about abstraction
and encapsulation.
Abstraction: It is a technique of hiding the internal details from the user and only showing
the necessary details to the user.
Encapsulation: It is a technique of combining the data and the member function in a single
unit is known as encapsulation.
The above figure shows the ADT model. There are two types of models in the ADT model, i.e., the
public function and the private function. The ADT model also contains the data structures that we
are using in a program. In this model, first encapsulation is performed, i.e., all the data is wrapped
in a single unit, i.e., ADT. Then, the abstraction is performed means showing the operations that
can be performed on the data structure and what are the data structures that we are using in a
program.

Let's understand the abstract data type with a real-world example.

If we consider the Smartphone, We look at the high specifications of the Smartphone,


such as:

o 4 GB RAM
o Snapdragon 2.2ghz processor
o 5 inch LCD screen
o Dual camera
o Android 8.0

The above specifications of the Smartphone are the data, and we can also perform the
following operations on the Smartphone:

o call(): We can call through the Smartphone.


o text(): We can text a message.
o photo(): We can click a photo.
o video(): We can also make a video.

The Smartphone is an entity whose data or specifications and operations are given above.
The abstract/logical view and operations are the abstract or logical views of a
Smartphone.
class Smartphone
{
private:
int ramSize;
string processorName;
float screenSize;
int cameraCount;
string androidVersion;
public:
void call();
void text();
void photo();
void video();
}
The above code is the implementation of the specifications and operations that can be performed on
the Smartphone. The implementation view can differ because the syntax of programming languages is
different, but the abstract/logical view of the data structure would remain the same. Therefore, we can
say that the abstract/logical view is independent of the implementation view.

Note: We know the operations that can be performed on the predefined data types such as
int, float, char, etc., but we don't know the implementation details of the data types.
Therefore, we can say that the abstract data type is considered as the hidden box that hides
all the internal details of the data type.

Common Data Structure Operations:


1. Access/Search:

Description: Finding the location of a particular element in the data structure.


Examples: Searching for an element in an array, finding a key in a hash
table.

2. Insertion:

Description: Adding a new element to the data structure.


Examples: Inserting a node into a linked list, adding an element to an array.

3. Deletion:
Description: Removing an element from the data structure.
Examples: Deleting a node from a linked list, removing an element from an
array.

4. Traversal:

Description: Visiting and processing each element in the data structure.


Examples: Iterating through elements in an array, traversing nodes in a tree.

5. Sorting:

Description: Arranging elements in a specified order.


Examples: Sorting an array using algorithms like quicksort or mergesort.

6. Merging:

Description: Combining two data structures into one.


Examples: Merging two sorted arrays or merging two sorted linked lists.

7. Splitting:

Description: Dividing a data structure into multiple parts.


Examples: Splitting an array into two halves or splitting a linked list.

Cost Estimation:
Time Complexity:

● Definition: Measures the amount of time an algorithm takes with


respect to its input size.
● Notation: Big O notation (O(f(n))).
● Example: If an algorithm’s time complexity is O(n), it means the
running time grows linearly with the input size.
Space Complexity:

● Definition: Measures the amount of memory an algorithm uses with


respect to its input size.
● Notation: Big O notation (O(f(n))).
● Example: If an algorithm’s space complexity is O(1), it means the
memory usage remains constant regardless of the input size.

Examples:
Array:

● Access/Search: O(1) – constant time if the index is known.


● Insertion/Deletion: O(n) – linear time for shifting elements.
● Traversal: O(n) – linear time to visit each element.

Linked List:

● Access/Search: O(n) – linear time to traverse the list.


● Insertion/Deletion: O(1) – constant time for adding/removing
elements at the beginning (with a reference to the head).
● Traversal: O(n) – linear time to visit each node.

Binary Search Tree:

● Access/Search: O(log n) – logarithmic time for balanced trees.


● Insertion/Deletion: O(log n) – logarithmic time for balanced trees.
● Traversal: O(n) – linear time for in-order traversal.

Hash Table:

● Access/Search/Insertion/Deletion: O(1) – constant time on average


for well-distributed hash functions.
● Traversal: O(n) – linear time to visit each element.
Array in Data Structure
In C programming, they are the derived data types that can store the primitive type of data such
as int, char, double, float, etc. For example, if we want to store the marks of a student in 6
subjects, then we don't need to define a different variable for the marks in different subjects.
Instead, we can define an array that can store the marks in each subject at the contiguous
memory locations.
Properties of array
There are some of the properties of an array that are listed as follows -
● Each element in an array is of the same data type and carries the same size that is 4
bytes.
● Elements in the array are stored at contiguous memory locations from which the first
element is stored at the smallest memory location.
● Elements of the array can be randomly accessed since we can calculate the address
of each element of the array with the given base address and the size of the data
element.

Representation of an array

We can represent an array in various ways in different programming languages. As an


illustration, let's see the declaration of array in C language

As per the above illustration, there are some of the following important points -

○ Index starts with 0.


○ The array's length is 10, which means we can store 10 elements.
○ Each element in the array can be accessed via its index.

Why are arrays required?

Arrays are useful because -

○ Sorting and searching a value in an array is easier.


○ Arrays are best to process multiple values quickly and easily.
○ Arrays are good for storing multiple values in a single variable - In computer
programming, most cases require storing a large number of data of a similar
type. To store such an amount of data, we need to define a large number of
variables. It would be very difficult to remember the names of all the variables
while writing the programs. Instead of naming all the variables with a different
name, it is better to define an array and store all the elements into it.

Memory allocation of an array

As stated above, all the data elements of an array are stored at contiguous locations in the
main memory. The name of the array represents the base address or the address of the
first element in the main memory. Each element of the array is represented by proper
indexing.

We can define the indexing of an array in the below ways -

1. 0 (zero-based indexing): The first element of the array will be arr[0].


2. 1 (one-based indexing): The first element of the array will be arr[1].
3. n (n - based indexing): The first element of the array can reside at any random index
number.

In the above image, we have shown the memory allocation of an array arr of size 5. The array
follows a 0-based indexing approach. The base address of the array is 100 bytes. It is the
address of arr[0]. Here, the size of the data type used is 4 bytes; therefore, each element will
take 4 bytes in the memory.

How to access an element from the array?

We required the information given below to access any random element from the array -
● Base Address of the array.
● Size of an element in bytes.
● Type of indexing, array follows.

The formula to calculate the address to access an array element -

Byte address of element A[i] = base address + size * ( i - first index)

Here, size represents the memory taken by the primitive data types. As an instance, int takes
2 bytes, float takes 4 bytes of memory space in C programming.

We can understand it with the help of an example -

Suppose an array, A[-10 ..... +2 ] having Base address (BA) = 999 and size of an element = 2
bytes, find the location of A[-1].

L(A[-1]) = 999 + 2 x [(-1) - (-10)]

= 999 + 18

= 1017

Basic operations

Now, let's discuss the basic operations supported in the array -

Traversal - This operation is used to print the elements of the array.


Insertion - It is used to add an element at a particular index.

Deletion - It is used to delete an element from a particular index.

Search - It is used to search an element using the given index or by the value.

Update - It updates an element at a particular index.

Traversal operation

This operation is performed to traverse through the array elements. It prints all array
elements one after another. We can understand it with the below program -

#include <stdio.h>
void main() {
int Arr[5] = {18, 30, 15, 70, 12};
int i;
printf("Elements of the array are:\n");
for(i = 0; i<5; i++) {
printf("Arr[%d] = %d, ", i, Arr[i]);
}
}

Insertion operation

This operation is performed to insert one or more elements into the array. As per the
requirements, an element can be added at the beginning, end, or at any index of the array.
Now, let's see the implementation of inserting an element into the array.

#include <stdio.h>
int main()
{
int arr[20] = { 18, 30, 15, 70, 12 };
int i, x, pos, n = 5;
printf("Array elements before insertion\n");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
x = 50; // element to be inserted
pos = 4;
n++;

for (i = n-1; i >= pos; i--)


arr[i] = arr[i - 1];
arr[pos - 1] = x;
printf("Array elements after insertion\n");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
Output

Deletion operation

As the name implies, this operation removes an element from the array and then
reorganizes all of the array elements.

#include <stdio.h>

void main() {
int arr[] = {18, 30, 15, 70, 12};
int k = 30, n = 5;
int i, j;

printf("Given array elements are :\n");

for(i = 0; i<n; i++) {


printf("arr[%d] = %d, ", i, arr[i]);
}

j = k;
while( j < n) {
arr[j-1] = arr[j];
j = j + 1;
}

n = n -1;

printf("\nElements of array after deletion:\n");

for(i = 0; i<n; i++) {


printf("arr[%d] = %d, ", i, arr[i]);
}
}
Output

Search operation

This operation is performed to search an element in the array based on the value or index.

#include <stdio.h>

void main() {
int arr[5] = {18, 30, 15, 70, 12};
int item = 70, i, j=0 ;

printf("Given array elements are :\n");

for(i = 0; i<5; i++) {


printf("arr[%d] = %d, ", i, arr[i]);
}
printf("\nElement to be searched = %d", item);
while( j < 5){
if( arr[j] == item ) {
break;
}

j = j + 1;
}

printf("\nElement %d is found at %d position", item, j+1);


}
Output

Update operation

This operation is performed to update an existing array element located at the given index.

#include <stdio.h>

void main() {
int arr[5] = {18, 30, 15, 70, 12};
int item = 50, i, pos = 3;

printf("Given array elements are :\n");

for(i = 0; i<5; i++) {


printf("arr[%d] = %d, ", i, arr[i]);
}

arr[pos-1] = item;
printf("\nArray elements after updation :\n");

for(i = 0; i<5; i++) {


printf("arr[%d] = %d, ", i, arr[i]);
}
}
Output
Complexity of Array operations
Time and space complexity of various array operations are described in the following table.

Time Complexity

Operation Average Case Worst Case

Access O(1) O(1)

Search O(n) O(n)

Insertion O(n) O(n)

Deletion O(n) O(n)

Space Complexity

In array, space complexity for worst case is O(n).

Advantages of Array
○ Array provides the single name for the group of variables of the same type.
Therefore, it is easy to remember the name of all the elements of an array.
○ Traversing an array is a very simple process; we just need to increment the base
address of the array in order to visit each element one by one.
○ Any element in the array can be directly accessed by using the index.

Disadvantages of Array
○ Array is homogenous. It means that the elements with similar data type can be
stored in it.
○ In array, there is static memory allocation that is size of an array cannot be
altered.
○ There will be wastage of memory if we store less number of elements than the
declared size.

You might also like