Ece Notes
Ece Notes
X Selection Sort - D.
geeksforgeeks.org
GEEKSFORGEEKS
Selection sort is a simple and efficient sorting algorithm that works by repeatedly selecting the smallest (or
largest) element from the unsorted portion of the list and moving it to the sorted portion of the list.
The algorithm repeatedly selects the smallest (or largest) element from the unsorted portion of the list and swaps
it with the first element of the unsorted part. This process is repeated for the remaining unsorted portion until the
entire list is sorted.
First pass:
" For the first position in the sorted array, the whole array is traversed from index 0 to 4 sequentially. The first
position where 64 is stored presently, after traversing whole array it is clear that 11 is the lowest value.
" Thus, replace 64 with 11. After one iteration 11, which happens to be the least value in the array, tends to
appear in the first position of the sorted list.
Swapping Elements
6425 12 22 11
Position to hold Min ele
Min element
Selection Sort
Selection Sort Algorithm | Swapping 1st element with the minimum in array
Second Pass:
" For the second position, where 25 is present, again traverse the rest of the array in a sequential manner.
" After traversing, we found that 12 is the second lowest value in the array and it should appear at the
second place in the array, thus swap these values.
Swapping
Min eleme
11 25 122264
already sorted Positiont
next min
Selection Sort
Selection Sort Algorithm | swapping i=1 with the next minimum element
Third Pass:
" Now, for third place, where 25 is present again traverse the rest of the array and find the third least value
7:03 0 D o Vo) 5 l 5%
" traverse from left and compare adjacent elements and the higher one is placed at right side.
In this way, the largest element is moved to the rightmost end at first.
" This process is then continued to find the second largest and place it and so on until the data is sorted.
Recommended Practice
Bubble Sort
Iry It!
How does Bubble Sort Work?
Let us understand the working of bubble sort with the help of the following illustration:
First Pass:
The largest element is placed in its correct position, ie.. the end of the array.
STEP
i=0 60T 3 5
4 4
i=1 06 3 5
i=2 O36 5
Sorted
0 35 6
Bubble sort
STEP
i=0 0356
3 5 6
O356
Sorted
Bubble sort
Bubble Sort Algorithm : Placing the second largest element at correct position
Third Pass:
Insertion sort is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and
the unsorted cards. Then, you pick a card from the unsorted group and put it in the right place in the sorted group.
Algorithm:
" We have to start with second element of the array as first element in the array is assumed to be sorted.
Compare second element with the first element and check if the second element is smaller then swap them.
" Move to the third element and compare it with the second element, then the first element and swap as
necessary to put it in the correct position among the first three elements
Continue this process,comparing each element with the ones before it and swapping as needed to place it in
the correct position among the sorted elements.
Repeat until the entire array is sorted.
Forth Pass 10 23 5 2 ’ 1 5 10 23 2
Fifth Pass 1 5 10 23|2 ’ 1 2 5 10 23
Insertion Sort
First Pass:
Second Pass:
Third Pass:
Fourth Pass:
" Compare 5 with1, 10, and 23 (current element with the sorted part).
" Since 5 is greater than 1 and smaller than 10, insert 5 between 1 and 10.
"The sorted part until 3rd index is: [1, 5, 10, 23]
Fifth Pass:
Compare 2 with 1,5, 10, and 23 (current element with the sorted part)
Since 2 is smaller than allelements in the sorted part, insert 2 at the beginning.
Open In App
5:47 b X" Vo) 5 16%L
QuickSort is a sorting algorithm based on the Divide and Conguer algorithmthat picks an element as a pivot
and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted
array.
The key process in quickSort is a partition). The target of partitions is to place the pivot (any element can be
chosen to be a pivot) at its correct position in the sorted array and put all smaller elements to the left of the
pivot, and all greater elements to the right of the pivot.
Partition is done recursively on each side of the pivot after the pivot is placed in its correct position and this
finally sorts the array.
Recommended Practice
Quick Sort
IryIt!
Choice of Pivot:
There are many different choices for picking pivots.
Partition Algorithm:
The logic is simple, we start from the leftmost element and keep track of the index of smaller (or equal)
elements as i. While traversing, if we find a smaller element, we swap the current element with arr[J.
Otherwise, we ignore the current element.
Let us understand the working of partition and the Quick Sort algorithm with the help of the following example:
Compare 10 with the pivot and as it is less than pivot arrange it accrodingly.
Pivot
10 80 30 90 40
Open In App
5:57 0Eb" o Vo) 56
LTº 15%
swap data
12
11
before deletion
https://www.andrew.cmu.edu »course
GeeksforGeeks
https://www.geeksforgeeks.org» h..
Share Save
ARRAY LINKEDLISTS
1Arays are stored in contiguous
location
1Linked lists are not stored in
contiguous location
Linked-List Array-List Winner?
2 FLxed in size 2. Dynamie in size. Dyanic memory aocation Stasc merory alocafos lallocated
doced duirg nun fmso ng onpia tiTHl Depends
3. Memory is allocated at compile tine. 3. Memory is allocated at run time
4, Uses less memory than linked lists Masory sa gPows ard s k s as Meroy sie is set wfo the amay
4. Uses more memory because it stores ode eleeets sre crstestemond is crened in iocks of memory Depends
both data and the address of next node
5. Elements can be arecessed easily. 5.Element accessing requires the Fiárg the r ctenerts soquires he
nction to frsveese the iet usti ths
Eerments in an aay can be
traversal of whole linked list indsed les arxyutinil rssching Array-Lit
value ha been neched Olnl ut vu in constart tme On
6 Insertion and deletion operation takes 6 Insertion and deletion operation is
time faster Eciert n teertg ard deieting Easy to iert ard delete on the
data n sry svsain nCNOe n isa porfd Alsn tees tme to Linked-List
eposon later elenerts wen an
s GeeksforGeeks mesory
ndx i t e tenond
Arryip Lirkal List spets ogential Ascess Seasctig ry warh asd inas sar ar
easet
akg t ades, lke anoj far le
dietty nalrkad li, e ba sqaetay oercts
*
Discover Search Saved
6:43 O M Vo) 5G
LTE JT g%
STACK QUEUE
1 Objects are inserted and removed at Objects are inserted and removed
th¿ same end. from different ends.
2 points
In stacks only one pointer is used. It
to the top of the stack.
In queues, two different pointers
are°used for front and rear ends.
Share Save
epbonis an Studerts stardrg n aine at fes couter is an ha oed cee poiser aré atvo prter varuhlcs.
2:43 e Merny Nege n keie uec
Logest) 2éngesn
lnee s s i t ised ie hoeSe syseetiknce ieteeere
rocedt ob sharieg
calledfoeL
Wocking UFO Last la Fin Ou) HFO Fst la First Cut)
tata
Principle
Variant Stack does noe hae variant Oueue has variants like cinculsr queue eae d
peiornity qcoe er n cat
etng
Undefined
What Is The Difference B..
In a priority queue, each element has a priority value associated with it. When you add an element to the queue, it
is inserted in a position based on its priority value. For example, if you add an element with a high priority value to
a priority queue, it may be inserted near the front of the queue, while an element with a low priority value may be
inserted near the back.
Aviator
INSTANTGAME
INSTANT WINS!
There are several ways to implementa priority queue, including using an array, linked list, heap, or binary search
tree. Each method has its own advantages and disadvantages, and the best choice will depend on the specific
needs of your application.
Priority queues are often used in real-time systems, where the order in which elements are processed can have
significant consequences. They are also used in algorithms to improve their efficiencies, such as Dijkstra's
algorithm for finding the shortest path in a graph and the A* search algorithm for pathfinding.
In the below priority queue, an element with a maximum ASCIl value will have the highest priority. The elements
with higher priority are served first.
Priority Queue
InitialQueue =()}
Operation Return value Queue Content
insert (C)
insert ( O) CO
insert ( D ) COD
remove ma> CD
insert () CDI
insert (N) CDIN
remove max N CDI
insert( G)
CDIG DG
Open In App
6:46 D Yo) 50 l 8%
deQueue is used for deleting an item from the queue. An item will be deleted from the front of a Queue only if
there is atleast one item in the queue. It's time complexity is constant i.e 0(1).
If the Queue is empty it returns -1 in Array implementation and NULL in Linked List representation.
3. front():
front() is used to retrieve the starting element of the queue. It's time complexity is constant.
If the Queue is empty it returns -1 in Array implementation and NULL in Linked List representation.
4. rear():
rear() is used to retrieve the last element of the queue. This operation takes O(1) time complexity.
If the Queue is empty it returns -1 in Array implementation and NULL in Linked List representation.
For more details about the operations and their implementation please refer to the article about "Circular Queue"
" In a page replacement algorithm, a circular list of pages is maintained and when a page needs to be replaced,
the page in the front of the queue will be chosen.
Computer systems supply a holding area for maintaining communication between two processes or two
programs. This memory area is also known as a ring buffer.
" CPU Scheduling: In the Round-Robin scheduling algorithm, a circular queue is utilized to maintain processes
that are in a ready state.
" Inter-process communication: Circular queue can be used for communication between different processes.
" Resource allocation: In operating systems, circular queue is used for managing resources.
" It provides a guick way to store FIFO data witha maximum size.
" Efficient utilization of the memory.
" Doesn't use dynamic memory.
" Simple implementation.
" Alloperations occur in O(1) constant time.
" Some operations like deletion or insertion can be complex in circular queue.
" The implementation of some algorithms like priority queue can be difficult in circular queue.
" Circular queue has a fixed size, and when it is full, there is a risk of overflow if not managed properly.
" In the array implementation of Circular Queue, even though it has space to insert the elements it shows that the
Circular Queue is full and gives the wrong size in some cases.
Recommended Articles
What is Tree?
A
tree data structure is a hierarchical data structure that consists of nodes connected by edges. Each node can
have multiple child nodes, but only one parent node. The topmost node in the tree is called the root node.
Google Workspace
Alexis
Worktogether
in real time with
live doc editing.
MDAD Sign up
Trees are often used to represent hierarchical data, such as file systems, XML documents, and organizational
charts.
A
collection of nodes (vertices) and A hierarchical data structure consisting of nodes
Definition
edges, where edges connect nodes. connected by edges with a single root node.
Can have cycles (loops) and No cycles; connected structure with exactly one
Structure
disconnected components. path between any two nodes.
Node Relationships between nodes are Parent-child relationship; each node (except the
Relationship arbitrary. root) has exactly one parent.
Each node can have any number of If there is n nodes then there would be n-1 number
Edges
edges. of edges
Used in various scenarios like Commonly used for hierarchical data representation
Application social networks, maps, network like file systems, organization charts, HTML DOM,
optimization, etc. XML documents, etc.
Recommended Articles
Open In App
6:51 " O Yo 5T l8%
and computer networks.
What is Tree?
A
tree data structure is a hierarchical data structure that consists of nodes connected by edges. Each node can
have multiple child nodes, but only one parent node. The topmost node in the tree is called the root node.
Google Workspace
Alexis
Worktogether
in real time with
live docediting.
MDAD Sign up
Trees are often used to represent hierarchical data, such as file systems, XML documents, and organizational
charts.
A
collection of nodes (vertices) and A hierarchical data structure consisting of nodes
Definition
edges, where edges connect nodes. connected by edges with a single root node.
Can have cycles (loops) and No cycles; connected structure with exactly one
Structure
disconnected components. path between any two nodes.
Node Relationships between nodes are Parent-child relationship; each node (except the
Relationship arbitrary. root) has exactly one parent.
Each node can have any number of If there is n nodes then there would be n-1 number
Edges
edges. of edges
Used in various scenarios like Commonly used for hierarchical data representation
Application social networks, maps, network like file systems, organization charts, HTML DOM,
optimization, etc. XML documents, etc.
Recommended Articles
Xlaomi 14
co:ENGINtEatD WITH
Leica
Next-GSOptical
ptica Lens
Starting 2916/month
Buy Now
"Music and Media Players: Circular linked lists can be used to implement playlists in music and media players.
Each node in the list can represent a song or media item, and the "next" pointer can point to the next song in
the playlist. When the end of the playlist is reached, the pointer can be set to the beginning of the list, creating
a circular structure that allows for continuous playback.
" Task Scheduling: Circular linked lists can be used to implement task scheduling algorithms, where each node
in the list represents a task and its priority. The "next" pointer can point to the next task in the queue, with the
end of the queue pointing back to the beginning to create a circular structure. This allows for a continuous loop
of task scheduling, where tasks are added and removed from the queue based on their priority.
"Cache Management: Circular linked lists can be used in cache management algorithms to manage the
replacement of cache entries. Each node in the list can represent a cache entry, with the "next" pointer pointing
to the next entry in the list. When the end of the list is reached, the pointer can be set to the beginning of the
list, creating a circular structure that allows for the replacement of older entries with newer ones.
" File System Management: Circular linked lists can be used in file system management to track the allocation of
disk space. Each node in the list can represent a block of disk space, with the "next" pointer pointing to the next
available block. When the end of the list is reached, the pointer can be set to the beginning of the list, creating a
circular structure that allows for the allocation and deallocation of disk space.
" Complexity: Circular linked lists can be more complex than other types of linked lists, especially when it comes
to algorithms for insertion and deletion operations. For example, determining the correct position for a new
node can be more difficult in a circular linked list than in a linear linked list.
" Memory leaks: If the pointers in a circular linked list are not managed properly, memory leaks can occur. This
happens when a node is removed from the list but its memory is not freed, leading to a buildup of unused
memory over time.
" Traversal can be more difficult: While traversal ofa circular linked list can be efficient, it can also be more
difficult than linear traversal, especially if the circular list has a complex structure. Traversing a circular linked
list requires careful management of the pointers to ensure that each node is visited exactly once.
" Lack of a natural end: The circular structure of the list can make it difficult to determine when the end of the
list has been reached. This can be a problem in certain applicatio ns, such as when processing a list of data in a
linear fashion.
Article Tags: Data Structures DSA Linked List circular linked list
ADVERTISEMENT
X
A regular sparse matrix is a square matrix with a well-defined sparsity pattern, i.e., non-zero elements
occur in a well-defined pattern. The various types of regular sparse matrices are:
ALower regular sparse matrix is the one where all elements above the main diagonal are zero value.
The following matrix is a lower triangular regular sparse matrix.
ADVERTISEMENT
1 0 00 0
9 -2 0 0 0
-2 1 3 0 0
3 1 -1 6 0
06 7 27
Lower Triangular
Matrix
In alower triangular regular sparse matrix, the non-zero elements are stored in a 1-dimensional array
row by row.
At
A21 A22
A31 A32 A33
A41 A42 A43 A44
As1 ’As2 ’As3 As4 >Ass
6:59 Vo) 5G
LTE J 7%
2 -1 -5 9 7
0 4 2 4 6
00 3 1 5
0 0 0 6 4
00 0 0 -2
Upper Triangular
Matrix
an upper triangular regular sparse matrix, the non-zero elements are stored in a 1-dimensional
array column by column.
For example,The 5 by 5 lower triangular regular sparse matrix, as shown in the above figure, is stored
in one-dimensional array B is:
ADVERTISEMENT
6:59 o Vo) 56 6%
Here C[1] =A11, C[2] =A12, C[3] =A22, C[4] =A13,C [5] =A23C [6] =A33, C[7] =A14,C [8] =Az4,C [9)
=A34, C[10]= A44 C[11]=A15,C [12] =Az5 c [13] =Ag5 ,C [14] =Aq5, C[15] =A55
In order to calculate the total number of non-zero elements, we need to know the number of non-zero
elements in each column and then add them. Since, the number of non-zero elements in ith column is
i so the total number of non-zero elements in upper triangular regular sparse matrix of n columns is:
ADVERTISEMENT
The tridiagonal regular sparse matrix where allnon-zero elements lie on one of the three diagonals,
the main diagonal above and below.
2 4 0 0 0
3 -1 5 0 0
06 2 1 0
00 1 -4 5
00 6 7
Tridiagonal Matrix
In a tri-diagonal regular sparse matrix, allthe non-zero elements are stored in a 1-dimensional array
row by row.
A1 ’A12
A21 A23 0
A32 A33
A43 44 Aas
A