0% found this document useful (0 votes)
5 views

Unit-1

Data structures are methods of organizing and storing data in computer memory for efficient retrieval and use, with two main types: linear and non-linear. Linear data structures include arrays, queues, stacks, and linked lists, while non-linear structures include graphs and trees. Abstract Data Types (ADTs) allow for defining data types independently of their implementation, focusing on operations rather than how they are executed.

Uploaded by

graunak197
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)
5 views

Unit-1

Data structures are methods of organizing and storing data in computer memory for efficient retrieval and use, with two main types: linear and non-linear. Linear data structures include arrays, queues, stacks, and linked lists, while non-linear structures include graphs and trees. Abstract Data Types (ADTs) allow for defining data types independently of their implementation, focusing on operations rather than how they are executed.

Uploaded by

graunak197
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/ 32

What is Data Structure

The data structure is a specific way of storing and organizing data in the computer's memory so
that these data can be easily retrieved and efficiently used when needed later.

The data can be managed in many different ways, such as a logical or mathematical model for a
particular organization of data is called a data structure.

For example, we have some data which has, player's name "Virat" and age 26. Here "Virat" is
of String data type and 26 is of integer data type.

Data Structures are the main part of many computer science algorithms as they enable the
programmers to handle the data in an efficient way. It plays a vitle role in enhancing the
performance of a software or a program as the main function of the software is to store and
retrieve the user’s data as fast as possible

Data structures can be subdivided into two major types:


● Linear Data Structure
● Non-linear Data Structure

Linear Data Structure


A data structure is said to be linear if its elements combine to form any specific order. There are
two techniques for representing such linear structure within memory.
● The first way is to provide a linear relationship between all the elements represented using
a linear memory location. These linear structures are called arrays.
● The second technique provides a linear relationship between all the elements represented
using the concept of pointers or links. These linear structures are called linked lists.
The typical examples of the linear data structure are:
● Arrays:An array is a collection of similar type of data items and each data item is called
an element of the array. The data type of the element may be any valid data type like char,
int, float or double.
The elements of array share the same variable name but each one carries a different index
number known as subscript. The array can be one dimensional, two dimensional or
multidimensional.

The individual elements of the array age are:

age[0], age[1], age[2], age[3],……… age[98], age[99].

● Queues: A queue is an important data structure in programming. A queue follows the FIFO
(First In First Out) method and is open at both of its ends. Data insertion is done at one end
rear end or the tail of the queue while deletion is done at the other end called the front end
or the head of the queue.

● Stacks: Stack is a linear list in which insertion and deletions are allowed only at one end,
called top.

● Linked lists: Linked list is a linear data structure which is used to maintain a list in the
memory. Each node of the list contains a pointer to its adjacent node.

Non-Linear Data Structure


This structure mainly represents data with a hierarchical relationship between different elements.
Examples of Non-Linear Data Structures are listed below:
● Graphs
● Family of trees and
● Table of contents

Basic types of Data Structures

Anything that can store data can be called as a data structure, hence Integer, Float, Boolean, Char
etc, all are data structures. They are known as Primitive Data Structures.
Then we also have some complex Data Structures, which are used to store large and connected
data. Some example of Abstract Data Structure are :
Linked List
Tree
Graph
Stack,Queue etc.
Operations on data structure

1) Traversing: Every data structure contains the set of data elements. Traversing the data structure
means visiting each element of the data structure in order to perform some specific operation like
searching or sorting.

Example: If we need to calculate the average of the marks obtained by a student in 6 different
subject, we need to traverse the complete array of marks and calculate the total sum, then we will
devide that sum by the number of subjects i.e. 6, in order to find the average.

2) Insertion: Insertion can be defined as the process of adding the elements to the data structure at
any location.

If the size of data structure is n then we can only insert n-1 data elements into it.

3) Deletion:The process of removing an element from the data structure is called Deletion. We can
delete an element from the data structure at any random location.

If we try to delete an element from an empty data structure then underflow occurs.

4) Searching: The process of finding the location of an element within the data structure is called
Searching. There are two algorithms to perform searching, Linear Search and Binary Search. We
will discuss each one of them later in this tutorial.
5) Sorting: The process of arranging the data structure in a specific order is known as Sorting.
There are many algorithms that can be used to perform sorting, for example, insertion sort,
selection sort, bubble sort, etc.

6) Merging: When two lists List A and List B of size M and N respectively, of similar type of
elements, clubbed or joined to produce the third list, List C of size (M+N), then this process is
called merging

CHAPTER I: ABSTRACT DATA TYPES

ABSTRACT DATA TYPES

● An abstract data type (or ADT) is a programmer-defined data type that specifies a
set of data values and a collection of well-defined operations that can be performed
on those values.

● Abstract data types are defined independent of their implementation, allowing us


to focus on the use of the new data type instead of how it'simplemented.

●The definition of ADT only mentions what operations are to be performed but not
how these operations will be implemented.
●The process of providing only the essentials and hiding the details is known as
abstraction.
The implementations of the various operations are hidden inside the black box, the
contents of which we do not have to know in order to utilize the ADT. There are several
advantages of working with abstract data types and focusing on the \what" instead of
the\how."
The user of data type does not need to know how that data type is implemented, for
example, we have been using Primitive values like int, float, char data types only with the
knowledge that these data type can operate and be performed on without any idea of how
they are implemented.

The implementation view of the above abstract/logical view is given below:


The above code is the implementation of the specifications and operations that can be
performed on the smartphone.

Now we’ll define three ADTs namely List ADT, Stack ADT, Queue ADT.

List ADT

● 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 List ADT Functions is given below:


● get() – Return an element from the list at any given position.
● insert() – Insert an element at any position of the list.
● remove() – Remove the first occurrence of any element from a non-empty list.
● removeAt() – Remove the element at a specified location from a non-empty list.
● replace() – Replace an element at any position by another element.
● size() – Return the number of elements in the list.
● isEmpty() – Return true if the list is empty, otherwise return false.
● isFull() – Return true if the list is full, otherwise return false.

Stack ADT
Stack is a linear data structure in which data can be only accessed from its top. It only has two
operations i.e. push (used to insert data to the stack top) and pop (used to remove data from the
stack top).

● push() – Insert an element at one end of the stack called top.


● pop() – Remove and return the element at the top of the stack, if it is not empty.
● peek() – Return the element at the top of the stack without removing it, if the stack is not
empty.
● size() – Return the number of elements in the stack.
● isEmpty() – Return true if the stack is empty, otherwise return false.
● isFull() – Return true if the stack is full, otherwise return false.

Queue ADT
Queue is a linear data structure in which data can be accessed from both of its ends i.e. front and
rear. It only has two operations i.e. push (used to insert data to the rear of the queue) and pop
(used to remove data from the front of the queue).
● enqueue() – Insert an element at the end of the queue.
● dequeue() – Remove and return the first element of the queue, if the queue is not empty.
● peek() – Return the element of the queue without removing it, if the queue is not empty.
● size() – Return the number of elements in the queue.
● isEmpty() – Return true if the queue is empty, otherwise return false.
● isFull() – Return true if the queue is full, otherwise return false.
Built-in Data Structures
As the name suggests, these Data Structures are built-in with Python which makes
programming easier and helps programmers use them to obtain solutions faster. Let’s
discuss each of them in detail.
Lists
Lists are used to store data of different data types in a sequential manner. There are
addresses assigned to every element of the list, which is called as Index. The index
value starts from 0 and goes on until the last element called the positive index. There is
also negative indexing which starts from -1 enabling you to access elements from the
last to first. Let us now understand lists better with the help of an example program.
Creating a list
To create a list, you use the square brackets and add elements into it accordingly. If you
do not pass any elements inside the square brackets, you get an empty list as the output.

Output:
[]
[1, 2, 3, ‘example’, 3.132]

Adding Elements
Adding the elements in the list can be achieved using the append(), extend() and insert()
functions.
● The append() function adds all the elements passed to it as a single element.
● The extend() function adds the elements one-by-one into the list.
● The insert() function adds the element passed to the index value and increase
the size of the list too.

Output:
[1, 2, 3]
[1, 2, 3, [555, 12]]
[1, 2, 3, [555, 12], 234, ‘more_example’]
[1, ‘insert_example’, 2, 3, [555, 12], 234, ‘more_example’]

Deleting Elements
● To delete elements, use the del keyword which is built-in into Python but this
does not return anything back to us.
● If you want the element back, you use the pop() function which takes the index
value.
● To remove an element by its value, you use the remove() function.

Output:
[1, 2, 3, ‘example’, 3.132, 30]
[1, 2, 3, 3.132, 30]
Popped Element: 2 List remaining: [1, 3, 3.132, 30]
[]

Accessing Elements
Accessing elements is the same as accessing Strings in Python. You pass the index
values and hence can obtain the values as needed.

Output:
1
2
3
example
3.132
10
30
[1, 2, 3, ‘example’, 3.132, 10, 30]
example
[1, 2]
[30, 10, 3.132, ‘example’, 3, 2, 1]

Other Functions
You have several other functions that can be used when working with lists.
● The len() function returns to us the length of the list.
● The index() function finds the index value of value passed where it has been
encountered the first time.
● The count() function finds the count of the value passed to it.
● The sorted() and sort() functions do the same thing, that is to sort the values of
the list. The sorted() has a return type whereas the sort() modifies the original list.

Output:
6
3
2
[1, 2, 3, 10, 10, 30]
[30, 10, 10, 3, 2, 1]

Dictionary
Dictionaries are used to store key-value pairs. To understand better, think of a phone
directory where hundreds and thousands of names and their corresponding numbers
have been added. Now the constant values here are Name and the Phone Numbers
which are called as the keys. And the various names and phone numbers are the values
that have been fed to the keys. If you access the values of the keys, you will obtain all
the names and phone numbers. So that is what a key-value pair is. And in Python, this
structure is stored using Dictionaries. Let us understand this better with an example
program.
Creating a Dictionary
Dictionaries can be created using the flower braces or using the dict() function. You
need to add the key-value pairs whenever you work with dictionaries.

Output:
{}
{1: ‘Python’, 2: ‘Java’}

Changing and Adding key, value pairs


To change the values of the dictionary, you need to do that using the keys. So, you firstly
access the key and then change the value accordingly. To add values, you simply just
add another key-value pair as shown below.

Deleting key, value pairs


● To delete the values, you use the pop() function which returns the value that has
been deleted.
● To retrieve the key-value pair, you use the popitem() function which returns a
tuple of the key and value.
● To clear the entire dictionary, you use the clear() function.
Accessing Elements
You can access elements using the keys only. You can use either the get() function or
just pass the key values and you will be retrieving the values.

Tuple
Tuples are the same as lists are with the exception that the data once entered into the
tuple cannot be changed no matter what. The only exception is when the data inside the
tuple is mutable, only then the tuple data can be changed. The example program will
help you understand better.
ARRAY

● The most basic structure for storing and accessing a collection of data is
the array.

● Arrays can be used to solve a wide range of problems in


computer science. Most Programming languages provide this
structured data type as a primitive and allow for the creation of
arrays with multiple dimensions.

● In this chapter, we implement an array structure for a one-


dimensional array and then use it to implement a Two-dimensional
array and the related matrix structure.

An array is a collection of items of the same variable type stored that


are stored at contiguous memory locations. It’s one of the most popular
and simple data structures and is often used to implement other data
structures. Each item in an array is indexed starting with 0.

Basic terminologies of array


● Array Index: In an array, elements are identified by their indexes. Array index
starts from 0.
● Array element: Elements are items stored in an array and can be accessed by
their index.
● Array Length: The length of an array is determined by the number of elements it
can contain.

Representation of Array
The representation of an array can be defined by its declaration. A declaration means
allocating memory for an array of a given size.
# Python code

arr = [10, 20, 30] # This array will store integer

arr2 = ['c', 'd', 'e'] # This array will store characters

arr3 = [28.5, 36.5, 40.2] # This array will store floating elements
Types of arrays:
There are majorly two types of arrays:
● One-Dimensional array: A One-Dimensional Array is the simplest form of an
Array in which the elements are stored linearly and can be accessed individually
by specifying the index value of each element stored in the array.

● data_type array_name [array_size] ;


● where,

● array_name = name of the 1D array

● array_size = defines the number of elements in the array

● Initialization Syntax

● To Initialize the 1D Array, we simply add a list to the right side of the declaration
syntax of the 1D Array. In simple terms, we assign values to the declared 1D Array
as per the array size specified.

● data_type array_name [array_size] = {comma_separated_element_list};




● Note: The number of elements specified in the list should not exceed the defined
Array Size.

● Example

● int arr [10] ; // Declaring a 1D array of size 10



● int roll_no [5] = {1, 2, 3, 4, 5} ; // Initializing a 1D array of size 5

● char names[30] = {"Raj, John, Krish"} ; // Initializing a 1D array of type char

1D array

● Two-dimensional array: 2-D Multidimensional arrays can be considered as an


array of arrays or as a matrix consisting of rows and columns.

int

2D array

Types of Array operations:


● Traversal: Traverse through the elements of an array.
● Insertion: Inserting a new element in an array.
● Deletion: Deleting element from the array.
● Searching: Search for an element in the array.
● Sorting: Maintaining the order of elements in the array.

Linear Search Algorithm

Searching is the process of finding some particular element in the list.


If the element is present in the list, then the process is called successful, and the process
returns the location of that element; otherwise, the search is called unsuccessful.

Two popular search methods are Linear Search and Binary Search.

Linear search is also called as sequential search algorithm.

It is the simplest searching algorithm.

In Linear search, we simply traverse the list completely and match each element of the
list with the item whose location is to be found.

If the match is found, then the location of the item is returned; otherwise, the algorithm
returns NULL.

It is widely used to search an element from the unordered list, i.e., the list in which items
are not sorted.

Linear search is implemented using following steps...


o Step 1 - Read the search element from the user.
o Step 2 - Compare the search element with the first element in the list.
o Step 3 - If both are matched, then display "Given element is found!!!" and
terminate the function
o Step 4 - If both are not matched, then compare search element with the next
element in the list.
o Step 5 - Repeat steps 3 and 4 until search element is compared with last element
in the list.
o Step 6 - If last element in the list also doesn't match, then display "Element is not
found!!!" and terminate the function.
o Algorithm
o Linear Search ( Array A, Value x)
o
o Step 1: Set i to 0
o Step 2: if i> n then go to step 7
o Step 3: if A[i] = x then go to step 6
o Step 4: Set i to i + 1
o Step 5: Go to Step 2
o Step 6: Print Element x Found at index i and go to step 8
o Step 7: Print element not found
o Step 8: Exit

Linear Search complexity


Now, let's see the time complexity of linear search in the best case, average case, and
worst case. We will also see the space complexity of linear search.

1. Time Complexity
Case Time Complexity

Best Case O(1)

Average Case O(n)

Worst Case O(n)

o Best Case Complexity - In Linear search, best case occurs when the element we
are finding is at the first position of the array. The best-case time complexity of
linear search is O(1).
o Average Case Complexity - The average case time complexity of linear search
is O(n).
o Worst Case Complexity - In Linear search, the worst case occurs when the
element we are looking is present at the end of the array. The worst-case in linear
search could be when the target element is not present in the given array, and we
have to traverse the entire array. The worst-case time complexity of linear search
is O(n).
The time complexity of linear search is O(n) because every element in the array is
compared only once.

Advantages of Linear Search:


● Linear search is simple to implement and easy to understand.
● Linear search can be used irrespective of whether the array is sorted or not. It
can be used on arrays of any data type.
● Does not require any additional memory.
● It is a well suited algorithm for small datasets.
Drawbacks of Linear Search:
● Linear search has a time complexity of O(n), which in turn makes it slow for
large datasets.
● Not suitable for large array.
● Linear search can be less efficient than other algorithms, such as hash tables.
When to use Linear Search:
● When we are dealing with a small dataset.
● When you need to find an exact value.
● When you are searching a dataset stored in contiguous memory.
● When you want to implement a simple algorithm.
Binary Search
Binary search is the search technique that works efficiently on sorted lists. Hence, to search an element into
some list using the binary search technique, we must ensure that the list is sorted.
Binary search follows the 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 the middle element
is returned. Otherwise, we search into either of the halves depending upon the result produced through the
match.

Algorithm
1. Binary_Search(a, lower_bound, upper_bound, val) // 'a' is the given array, 'lower_bound' is the index of
the first array element, 'upper_bound' is the index of the last array element, 'val' is the value to search
2. Step 1: set beg = lower_bound, end = upper_bound, pos = - 1
3. Step 2: repeat steps 3 and 4 while beg <=end
4. Step 3: set mid = (beg + end)/2
5. Step 4: if a[mid] = val
6. set pos = mid
7. print pos
8. go to step 6
9. else if a[mid] > val
10. set end = mid - 1
11. else
12. set beg = mid + 1
13. [end of if]
14. [end of loop]
15. Step 5: if pos = -1
16. print "value is not present in the array"
17. [end of if]
18. Step 6: exit

Example:Refer which are done in classroom.

Binary Search Algorithm: The basic steps to perform Binary Search are:
●Sort the array in ascending order.
●Set the low index to the first element of the array and the high index to the last element.
●Set the middle index to the average of the low and high indices.
●If the element at the middle index is the target element, return the middle index.
●If the target element is less than the element at the middle index, set the high index to the middle
index – 1.
●If the target element is greater than the element at the middle index, set the low index to the
middle index + 1.
●Repeat steps 3-6 until the element is found or it is clear that the element is not present in the
array.

Advantages of Binary Search:


●Binary search is faster than linear search, especially for large arrays. As the size of the array
increases, the time it takes to perform a linear search increases linearly, while the time it takes to
perform a binary search increases logarithmically.
●Binary search is more efficient than other searching algorithms that have a similar time
complexity, such as interpolation search or exponential search.
●Binary search is relatively simple to implement and easy to understand, making it a good choice
for many applications.
●Binary search can be used on both sorted arrays and sorted linked lists, making it a flexible
algorithm.
●Binary search is well-suited for searching large datasets that are stored in external memory,
such as on a hard drive or in the cloud.
●Binary search can be used as a building block for more complex algorithms, such as those used
in computer graphics and machine learning.
Drawbacks of Binary Search:
●We require the array to be sorted. If the array is not sorted, we must first sort it before
performing the search. This adds an additional O(n log n) time complexity for the sorting
step, which can make binary search less efficient for very small arrays.
●Binary search requires that the array being searched be stored in contiguous memory locations.
This can be a problem if the array is too large to fit in memory, or if the array is stored on
external memory such as a hard drive or in the cloud.
●Binary search requires that the elements of the array be comparable, meaning that they must be
able to be ordered. This can be a problem if the elements of the array are not naturally
ordered, or if the ordering is not well-defined.
●Binary search can be less efficient than other algorithms, such as hash tables, for searching very
large datasets that do not fit in memory.
Applications of Binary search:
●Searching in machine learning: Binary search can be used as a building block for more complex
algorithms used in machine learning, such as algorithms for training neural networks or
finding the optimal hyperparameters for a model.
●Commonly used in Competitive Programming.
●Can be used for searching in computer graphics. Binary search can be used as a building block
for more complex algorithms used in computer graphics, such as algorithms for ray tracing
or texture mapping.
●Can be used for searching a database. Binary search can be used to efficiently search a
database of records, such as a customer database or a product catalog.
When to use Binary Search:
●When searching a large dataset as it has a time complexity of O(log n), which means that it is
much faster than linear search.
●When the dataset is sorted.
●When data is stored in contiguous memory.
●Data does not have a complex structure or relationships.

Bubble Sort

Bubble Sort is a simple algorithm which is used to sort a given set of n elements
provided in form of an array with n number of elements. Bubble Sort compares all the
element one by one and sort them based on their values.
If the given array has to be sorted in ascending order, then bubble sort will start by
comparing the first element of the array with the second element, if the first element is
greater than the second element, it will swap both the elements, and then move on to
compare the second and the third element, and so on.
If we have total n elements, then we need to repeat this process for n-1 times.
It is known as bubble sort, because with every complete iteration the largest element in
the given array, bubbles up towards the last place or the highest index, just like a water
bubble rises up to the water surface.
Sorting takes place by stepping through all the elements one-by-one and comparing it
with the adjacent element and swapping them if required.

Implementing Bubble Sort Algorithm

Following are the steps involved in bubble sort(for sorting a given array in ascending
order):
1. Starting with the first element(index = 0), compare the current element with the
next element of the array.

2. If the current element is greater than the next element of the array, swap them.

3. If the current element is less than the next element, move to the next
element. Repeat Step 1.

Algorithm
In the algorithm given below, suppose arr is an array of n elements. The
assumed swap function in the algorithm will swap the values of given array elements.
1. begin BubbleSort(arr)
2. for all array elements
3. if arr[i] > arr[i+1]
4. swap(arr[i], arr[i+1])
5. end if
6. end for
7. return arr
8. end BubbleSort

Working of Bubble sort Algorithm


Now, let's see the working of Bubble sort Algorithm.To understand the working of bubble
sort algorithm, let's take an unsorted array.
Let the elements of array are -

First Pass
Sorting will start from the initial two elements. Let compare them to check which is
greater.

Here, 32 is greater than 13 (32 > 13), so it is already sorted. Now, compare 32 with 26.

Here, 26 is smaller than 36. So, swapping is required. After swapping new array will look
like -

Now, compare 32 and 35.

Here, 35 is greater than 32. So, there is no swapping required as they are already sorted.
Now, the comparison will be in between 35 and 10.

Here, 10 is smaller than 35 that are not sorted. So, swapping is required. Now, we reach
at the end of the array. After first pass, the array will be -

Now, move to the second iteration.

Second Pass
The same process will be followed for second iteration.

Here, 10 is smaller than 32. So, swapping is required. After swapping, the array will be -

Now, move to the third iteration.


Third Pass
The same process will be followed for third iteration.

Here, 10 is smaller than 26. So, swapping is required. After swapping, the array will be -

Now, move to the fourth iteration.

Fourth pass
Similarly, after the fourth iteration, the array will be -
Hence, there is no swapping required, so the array is completely sorted.
Bubble sort complexity
Now, let's see the time complexity of bubble sort in the best case, average case, and
worst case. We will also see the space complexity of bubble sort.

1. Time Complexity
Case Time Complexity

Best Case O(n)


2
Average Case O(n )
2
Worst Case O(n )

o Best Case Complexity - It occurs when there is no sorting required, i.e. the array
is already sorted. The best-case time complexity of bubble sort is O(n).
o Average Case Complexity - It occurs when the array elements are in jumbled
order that is not properly ascending and not properly descending. The average
2
case time complexity of bubble sort is O(n ).
o Worst Case Complexity - It occurs when the array elements are required to be
sorted in reverse order. That means suppose you have to sort the array elements
in ascending order, but its elements are in descending order. The worst-case time
2
complexity of bubble sort is O(n ).

Advantages:
●Bubble sort is easy to understand and implement.
●It does not require any additional memory space.
●It’s adaptability to different types of data.
Disadvantages
●Bubble sort has a time complexity of O(n^2) which makes it very slow for large data sets.
●It is not efficient for large data sets, because it requires multiple passes through the data.
●It is not a stable sorting algorithm, meaning that elements with the same key value may not
maintain their relative order in the sorted output.
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. It is also the simplest algorithm. It is an in-place comparison
sorting algorithm. In this algorithm, the array is divided into two parts, first is sorted part, and another one is the
unsorted part. Initially, the sorted part of the array is empty, and unsorted part is the given array. Sorted part is
placed at the left, while the unsorted part is placed at the right.
In selection sort, the first smallest element is selected from the unsorted array and placed at the first position.
After that second smallest element is selected and placed in the second position. The process continues until
the array is entirely sorted.
Selection sort is generally used when -
o A small array is to be sorted
o Swapping cost doesn't matter
o It is compulsory to check all elements

Working of Selection sort Algorithm


Now, let's see the working of the Selection sort Algorithm.
To understand the working of the Selection sort algorithm, let's take an unsorted array. It will be easier
to understand the Selection sort via an example.
Let the elements of array are -

Now, for the first position in the sorted array, the entire array is to be scanned sequentially.
At present, 12 is stored at the first position, after searching the entire array, it is found that 8 is the
smallest value.

So, swap 12 with 8. After the first iteration, 8 will appear at the first position in the sorted array.

For the second position, where 29 is stored presently, we again sequentially scan the rest of the items
of unsorted array. After scanning, we find that 12 is the second lowest element in the array that should
be appeared at second position.
Now, swap 29 with 12. After the second iteration, 12 will appear at the second position in the sorted
array. So, after two iterations, the two smallest values are placed at the beginning in a sorted way.

The same process is applied to the rest of the array elements. Now, we are showing a pictorial
representation of the entire sorting process.

Now, the array is completely sorted.

Advantages of Selection Sort Algorithm:


● Simple and easy to understand.
● Preserves the relative order of items with equal keys which means it is stable.
● Works well with small datasets.
● It is adaptable to various types of data types.
● Selection sort is an in-place sorting algorithm, which means it does not require any
additional memory to sort the list.
● It is easy to modify to sort in ascending or descending order.It can be easily implemented in
hardware, making it suitable for real-time applications.
Dis-advantages of Selection Sort Algorithm:
●Does not works well on large datasets.
●Selection sort algorithm needs to iterate over the list multiple times, thus it can lead to an
unbalanced branch.
●Selection sort has poor cache performance and hence it is not cache friendly.
●Not adaptive, meaning it doesn’t take advantage of the fact that the list may already be sorted
or partially sorted
●Not a good choice for large data sets with slow random access memory (RAM)
●It’s not a comparison sort and doesn’t have any performance guarantees like merge sort or
quick sort.
●It has poor cache performance

You might also like