Structured_Unit_II_Notes
Structured_Unit_II_Notes
Unit II:
Linear Data Structures, Searching and Sorting
Dinesh Satre
[Link]@[Link]
SEQUENTIAL ORGANIZATION
If the ith element is stored at location X, then the
SEQUENTIAL ORGANIZATION
As sequential organization uses continuous memory locations to store data, the data
access time remains constant for accessing any element of the list
SEQUENTIAL ORGANIZATION
So the in-between insertions and deletions become much expensive with respect to
Array:
Arrays support direct access to any of those data items just by specifying the name of the
array and its
Array:
Enable us to organize more than one element in consecutive memory locations. Hence, it is
also termed
The only restriction is that all the elements must be of the same data type.
Arrays are the most general and easy to use of all the data structures.
An array as a data structure is defined as a set of pairs (index, value) such that with
Ordered collection: The arrangement of all the elements in an array is very specific, that is,
every
Homogeneous: All the elements of an array should be of the same data type.
int Array_A[20];
This statement will allocate a memory space to store 20 integer elements, and the
Array_A
1
2
10
11
12
13
14
15
16
17
18
19
Size of array:
The maximum number of elements that would be stored in an array is the size of that array.
Arrays are Static Data Structures because once the size of an array is defined, it cannot be
changed
after compilation.
Array_A
10
11
12
13
14
15
16
17
18
19
LINEAR DATA STRUCTURE USING ARRAYS
Base Address:
The base address of an array is the memory location where the first element of an array is
stored.
The value of this base address varies at every program execution as it is decided at the run-
time.
Data type of an array: The data type of an array indicates the data type of elements
subscripts such as Name[0], Name[1], ..., Name[i]. This subscript is called the index
of an element. It indicates the relative position of every element in the array with
respect to its first element. Often, an array is also referred to as subscripted variable.
For defining an array as an abstract data type (ADT), we have to define the very basic
operations or functions that can be performed on it.
Creating an array
Storing an element
Accessing an element
be performed.
Access() takes an array and an index as input, and returns either the appropriate value
or an error.
Domain: A domain is the intended set of values that any array may use either as an
index or as a value.
We can say that a domain of an array is a collection of fixed, homogeneous elements that
may be atomic
or structured.
Arrays use a set of indices or subscript values that have one-to-one correspondence with
the positive
integer values.
During compilation, the appropriate number of locations is allocated for the array.
So if the ith element is mapped into a memory location of address x, then the (i + 1)th
element is mapped
address)
storage starts.
of each element)
Operations on Array
Searching an Element forma an Array
Update an Element
10
20
30
10
20
30
40
To insert an element at the ith position in an array of size N, all the elements originally at
positions i, i +
Deleting an Element
After one deletion operation, one location becomes empty, so all the elements should
be shifted by one position after the deleted element to fill in the empty location of the
deleted element.
Searching an Element
Searching finds the index location of a given target value within the array
Search for 30
Check index 0: 10 != 30
Check index 1: 20 != 30
○
10
20
30
40
50
Updating an Element
Updating changes the value stored at a specific index. Because arrays support
random access via index arithmetic, updating an element takes place instantly.
Execute A[2] = 99
10
20
30
40
50
10
20
99
40
50
Traversal means accessing or visiting every element in the array sequentially, usually
to print, modify, or run calculations on the data (like finding a total sum)
10
20
30
40
50
MULTIDIMENSIONAL ARRAYS
multiple dimensions.
two-dimensional, three-dimensional, or
n-dimensional arrays.
MULTIDIMENSIONAL ARRAYS
One-dimensional Array To Multi Dimensional Array
Two-dimensional Arrays
A two-dimensional array A of dimension m X n is
For the C/C++ languages this range is 0 ≤ i < m
and 0 ≤ j < n.
columns.
Two-dimensional Arrays
memory as
Row-major representation
Column-major representation
Row-major Representation
In row-major representation, the elements of matrix M are stored row-wise, that is,
elements of the 0th row, 1st row, 2nd row, 3rd row, and so on till the mth row.
Row-major Representation
The address of the element of the ith row and the jth column for a matrix of size m X n
can be calculated as
Address of (A[i][j]) =
Row-major Representation
Address of A[i][j] =
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
Column-major Representation
The elements are stored in the memory as a sequence: first the elements of column 0,
then the elements of column 1, and so on, till the elements of column n - 1.
Column-major Representation
1000
1012
1024
1036
1004
1016
1028
1040
1008
1020
1032
1044
Column-major Representation
Address of (A[i][j]) = Base address + ((j * m ) + i )* Size of element
1000
1003
1006
1009
1001
1004
1007
1010
1002
1005
1008
1011
Row-major
Fortran
Column-major
MATLAB
Column-major
Python (NumPy)
Java
Row-major
EXAMPLE
Consider an integer array, int A[3][4] in C++. If the base address is 1050, find the
the array.
Solution: For C++, the LB of index is 0, and we have m = 3, n = 4, and Base = 1050.
Let us compute the address of the element A[2][3] using the address computation
formula
EXAMPLE
EXAMPLE
Example-2
Find the address offset of A[2][1] in both layouts (using 0-based index)
Example-2
Find the address offset of A[2][1] in both layouts (using 0-based index)
Row Major:
Column Major:
= 1000 + (1 * 3) + 2) * 4 = 1020
Q&A
1. Which of the following best describes an array?
Q&A
2. What is the primary advantage of using an array?
C. Dynamic resizing
Q&A
3. Which of the following is not a valid operation on an array?
A. Traversal
B. Insertion
C. Deletion
D. Hashing
Q&A
4. Arrays are considered as which type of Abstract Data Type (ADT)?
A. Linear ADT
B. Non-linear ADT
C. Hierarchical ADT
D. Graph-based ADT
Q&A
5. What happens when an element is inserted into the middle of an array?
Q&A
6. What is the worst-case time complexity of searching an element in an unsorted
array?
A. O(1)
B. O(log n)
C. O(n)
D. O(n log n)
Q&A
7. In memory, array elements are stored:
Q&A
8. In C/C++, how is the address of the ith element of a 1D array A computed?
A. Base_Address + i * sizeof(datatype)
B. Base_Address + i
C. i + sizeof(datatype)
D. Base_Address * i
Q&A
9. Which of the following best describes a two-dimensional array?
A. A list of arrays
B. A linear sequence
C. A tree structure
D. A hash table
Q&A
10. If int A[3][4]; is declared in C, how many elements does the array have?
A. 3
B. 4
C. 7
D. 12
Q&A
11. In a row-major storage of a 2D array, which element comes first in memory?
Q&A
12. Which of the following is true about multidimensional arrays in most
programming languages?
SPARSE MATRIX
To represent a matrix, we need a two-dimensional array with two different indices for
The representation of a matrix for operations on it should be efficient so that the space
In many situations, the matrix size is very large but most of the elements in it are 0s
SPARSE MATRIX
The sparse matrix must be represented and stored with an alternate way to achieve
SPARSE MATRIX
Sparse square matrix
A triple (i, j, value) can easily represent the non-zero elements of the matrix.
be added.
B, respectively.
matrix.
A=
B=
transpose of the matrix as the elements at position [i][j] and [j][i] are swapped
them further.
Simple Transpose
Let A be a matrix of size m X n with T non-zero elements and let B be its transpose.
One of the easiest ways is to search for each column (column = 0 to n - 1) and
sequentially place each column as a row in the transposed matrix B by placing the
Simple Transpose
Simple Transpose
In Algorithm, we first take the first row of matrix A as (m,
Simple Transpose
Find the transpose of sparse matrix using simple transpose method
Fast Transpose
Let A be a sparse matrix of size m X n with T non-zero elements. Its transpose will be
stored in matrix B.
RowStartPos will be computed and stored at the position where each row entry of
Fast Transpose
Fast Transpose
This algorithm will first find the number of non-zero elements in each column and
The second array RowStartPos is used to store the starting address of each column,
Fast Transpose
Fast Transpose
Freq
3
1
RowStartPos
Q&A
What defines a sparse matrix?
a) A matrix with all elements equal to zero
b) A matrix with most elements equal to zero
c) A matrix with all diagonal elements equal to one
d) A matrix with an equal number of non-zero and zero elements
Q&A
What is the primary advantage of using sparse matrix representations?
a) Reduced memory usage
b) Faster computation
c) Simplified matrix operations
d) All of the above
Q&A
When adding two sparse matrices, what is the time complexity?
a) O(n)
b) O(m + n)
c) O(n²)
d) O(1)
Q&A
What is the main difference between simple transpose and fast transpose of a
sparse matrix?
a) Simple transpose uses extra space, while fast transpose does not
b) Fast transpose is more efficient in terms of time complexity
c) Simple transpose is used for dense matrices only
d) There is no difference; they are the same
Q&A
In the fast transpose algorithm, what is the purpose of the 'index' array?
a) To store the row indices of non-zero elements
b) To store the column indices of non-zero elements
c) To keep track of the position of elements in the transposed matrix
d) To store the values of non-zero elements
Q&A
In the context of sparse matrices, what does the term 'sparsity' refer to?
a) The ratio of non-zero elements to total elements
b) The ratio of zero elements to total elements
c) The number of rows in the matrix
d) The number of columns in the matrix
Searching
The process of locating target data is known as searching.
Consider a situation where you are trying to get the phone number of your friend from a
telephone
directory. The telephone directory can be thought of as a table or a file, which is a collection
of records.
Each record has one or more fields such as name, address, and telephone number.
The fields, which are used to distinguish records, are known as keys.
While searching, we are asked to find the record which contains information along with
the target key. When we think of a telephone directory, the search is usually by name.
Searching
If the key is unique and if it determines a record uniquely, it is called a primary key.
always be unique. For example, if we use ‘name’ as the key for a telephone directory,
Searching
We may use one of the two linear data structures, arrays and linked lists, for storing the
data.
If the search is applied on the table that resides at the secondary storage (hard disk), it is
(main memory) is called as internal searching which is faster than external searching.
Searching
A searching algorithm accepts two arguments as parameters—a target value to be
The search algorithm searches a target value in the list until the target key is found or
Search techniques
Depending on the way data is scanned for searching a particular record, the search
1. Sequential search
○
2. Binary search
3. Fibonacci search
given to order, or when the storage medium lacks any type of direct access facility.
For example, magnetic tape and linked list are sequential storage media where the
Let us assume that we have a sequential file F, and we wish to retrieve a record with a
If F has n records, then key retrieval is by examining the key values in the order
A sequential search begins with the first available record and proceeds to the next
available record repeatedly until we find the target key or conclude that it is not found.
the array A where the element is to be searched, and the total number of elements in the
array.
The function SeqSearch() returns the location of the element if found or returns -1 if the
data.
list.
If the target data is placed at the first location, we get it in just one comparison.
Similarly, i comparisons are required if the target data is at the ith location and n
Pros
4. Suitable for storage structures which do not support direct access to data, for
5. Best case is one comparison, worst case is n comparisons, and average case is (n +
1)/2 comparisons
Cons
2. In the case of ordered data other search techniques such as binary search are found
more suitable.
the best case, n comparisons in the worst case, and (n + 1)/2 comparisons in the average
case. The algorithm starts at the first location and the search continues till the last
element. We can make a few changes leading to a few variations in the sequential
search algorithm.
1. Sentinel search
2. Probability search
Sentinel search
We note that in Sequential Algorithm, there are two comparisons one for the element
(key) to be searched and the other for the end of the array. The algorithm ends either
The algorithm can be modified to eliminate the end of list test by placing the target at
the end of list as just one additional entry. This additional entry at the end of the list is
called as a sentinel.
Now, we need not test for the end of list condition within the loop and merely check
after the loop completes whether we found the actual target or the sentinel. This
modification avoids one comparison within the loop that varies n times. The only care
Sentinel search
Probability search
In probability search, the elements that are more probable are placed at the beginning
of the array and those that are less probable are placed at the end of the array.
However, when data is ordered and is of smaller size, sequential search with a small
In addition, when the data is ordered but stored in a data structure such as a linked list,
While searching an ordered list, we need not continue the search till the end of list to
know that the target element is not in the list. While searching in an ascending ordered
list, whenever an element that is greater than or equal to the target is encountered, the
search stops. We can also add a sentinel to avoid the end of list test.
Q&A
Which of the following statements about sequential search is TRUE?
Q&A
In sentinel search, what is placed at the end of the array?
A. The maximum element
C. A null value
Q&A
Probability search improves performance by:
B. Removing duplicates
Q&A
In probability search, which of the following operations is typically performed after a
successful search?
Q&A
Ordered list search can stop early if:
Binary Search
Sequential search is not suitable for larger lists. It requires n comparisons in the worst
case.
In binary search, as we have divided the list to be searched every time into two lists and
In binary search algorithm, to search for a particular element, it is first compared with
the element at the middle position, and if it is found, the search is successful, else if the
middle position value is greater than the target, the search will continue in the first half
of the list; otherwise, the target will be searched in the second half of the list.
Binary Search
Binary Search
Binary Search
Binary Search
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
x = 10
Low = 1
High = 14
Mid = (1+14)/2 = 7
Binary Search
Let us consider the list
Time complexity of binary search is O(log(n)) as it halves the list size in each step.
occurrences disappear.
Binary Search
The recurrence relation for Binary Search
Recurrence relation for D&C is
Therefore,
–a = 1
–b = 2
f(n) = 1
Binary Search
If f (n) ∈ Ө(nd) where d ≥ 0
Then, d = 0, since f(n) = 1
According to master theorem,
Therefore,
Since, a = bd
Fibonacci search
The Fibonacci series has 0 and 1 as the first two terms, and each successive term is the
Fibonacci search
The detailed procedure of the searching is seen below
Step 1 − As the first step, find the immediate Fibonacci number that is greater than or
equal to the size of the input array. Then, also hold the two preceding numbers of the
selected Fibonacci number, that is, we hold Fm, Fm-1, Fm-2 numbers from the
Fibonacci Series.
Step 2 − Initialize the offset value as -1, as we are considering the entire array as the
Fibonacci search
○
Compare the key element to be found with the element at index i = [min(offset+Fm-2,n-1)].
If a
If the key element is found to be lesser value than this element, we reduce the range of the
input
from 0 to the index of this element. The Fibonacci numbers are also updated with Fm = Fm-
2.
But if the key element is greater than the element at this index, we remove the elements
before
this element from the search range. The Fibonacci numbers are updated as Fm = Fm-1.
Fibonacci search
The detailed procedure of the searching is seen below
Step 4 − As there are two 1s in the Fibonacci series, there arises a case where your two
preceding numbers will become 1. So if Fm-1 becomes 1, there is only one element left
in the array to be searched. We compare the key element with that element and return
Example
Suppose we have a sorted array of elements {12, 14, 16, 17, 20, 24, 31, 43, 50, 62} and
Example
Suppose we have a sorted array of elements {12, 14, 16, 17, 20, 24, 31, 43, 50, 62} and
Step 1
The size of the input array is 10. The smallest Fibonacci number greater than 10 is 13.
Therefore, Fm = 13, Fm-1 = 8, Fm-2 = 5.
We initialize offset = -1
Example
Suppose we have a sorted array of elements {12, 14, 16, 17, 20, 24, 31, 43, 50, 62} and
Step 2
In the first iteration, compare it with the element at index = minimum (offset + Fm-2, n
Example
Suppose we have a sorted array of elements {12, 14, 16, 17, 20, 24, 31, 43, 50, 62} and
Step 3
In the second iteration, update the offset value and the Fibonacci numbers.
Since the key is greater, the offset value will become the index of the element, i.e. 4.
Fm-1 = 5, Fm-2 = 3.
Example
Suppose we have a sorted array of elements {12, 14, 16, 17, 20, 24, 31, 43, 50, 62} and
Now, compare it with the element at index = minimum (offset + Fm-2, n 1) = minimum
(4 + 3, 9) = minimum (7, 9) = 7.
Example
Suppose we have a sorted array of elements {12, 14, 16, 17, 20, 24, 31, 43, 50, 62} and
Step 4
We discard the elements after the 7th index, so n = 7 and offset value remains 4.
Fibonacci numbers are pushed two steps backward, i.e. Fm = Fm-2 = 3.
Fm-1 = 2, Fm-2 = 1.
Example
Suppose we have a sorted array of elements {12, 14, 16, 17, 20, 24, 31, 43, 50, 62} and
Now, compare it with the element at index = minimum (offset + Fm-2, n 1) = minimum
(4 + 1, 6) = minimum (5, 7) = 5.
Example-2
Search for 81 using Fibonacci search in the list {6, 14, 23, 36, 55, 67, 76, 78, 81, 89},
where n = 10.
Step 1
The size of the input array is 10. The smallest Fibonacci number greater than 10 is 13.
Therefore, Fm = 13, Fm-1 = 8, Fm-2 = 5.
We initialize offset = -1
Example-2
Search for 81 using Fibonacci search in the list {6, 14, 23, 36, 55, 67, 76, 78, 81, 89},
where n = 10.
Step 2
In the first iteration, compare it with the element at index = minimum (offset + Fm-2, n
14
23
36
55
67
76
78
81
89
3
4
Example-2
Search for 81 using Fibonacci search in the list {6, 14, 23, 36, 55, 67, 76, 78, 81, 89},
where n = 10.
Step 3
In the second iteration, update the offset value and the Fibonacci numbers.
Since the key is greater, the offset value will become the index of the element, i.e. 4.
Fm-1 = 5, Fm-2 = 3.
Example-2
Search for 81 using Fibonacci search in the list {6, 14, 23, 36, 55, 67, 76, 78, 81, 89},
where n = 10.
Now, compare it with the element at index = minimum (offset + Fm-2, n 1) = minimum
(4 + 3, 9) = minimum (7, 9) = 7.
14
23
36
55
67
76
78
81
89
Example-2
Search for 81 using Fibonacci search in the list {6, 14, 23, 36, 55, 67, 76, 78, 81, 89},
where n = 10.
Step 4
In the third iteration, update the offset value and the Fibonacci numbers.
Since the key is greater, the offset value will become the index of the element, i.e. 7.
Fm-1 = 3, Fm-2 = 2.
Example-2
Search for 81 using Fibonacci search in the list {6, 14, 23, 36, 55, 67, 76, 78, 81, 89},
where n = 10.
Now, compare it with the element at index = minimum (offset + Fm-2, n-1) = minimum
(7 + 2, 9) = minimum (9, 9) = 9.
14
23
36
55
67
76
78
81
89
Example-2
Search for 81 using Fibonacci search in the list {6, 14, 23, 36, 55, 67, 76, 78, 81, 89},
where n = 10.
Step 5
We discard the elements after the 9th index, so n = 9 and offset value remains 7.
Fibonacci numbers are pushed two steps backward, i.e. Fm = Fm-2 = 3.
Fm-1 = 2, Fm-2 = 1.
Example-2
Search for 81 using Fibonacci search in the list {6, 14, 23, 36, 55, 67, 76, 78, 81, 89},
where n = 10.
Now, compare it with the element at index = minimum (offset + Fm-2, n-1) = minimum
(7 + 1, 9) = minimum (8, 8) = 8.
14
23
36
55
67
76
78
81
89
Algorithm
to be searched once.
Since this is a small-scale example, binary search will score, but in larger instances, it
Fibonacci search is more efficient than binary search for large lists.
However, it is inefficient in case of small lists.
Con
An index file can be used to effectively overcome the problem associated with
Only a subset of data records,evenly spaced along the data file, is indexed to mark the
the search key is compared with the index to find the highest index key
preceding the search, and a linear search is performed from the current record
until the search key is matched or until the record pointed by the next index entry
is reached.
In spite of the double file access (index + data) needed by this kind of search, the
1. The index file is ordered, so the searching can be done using the binary search method.
3. The record position is used to access the details of that record from the data file.
Example
Consider a sorted array of integers: arr = {6, 7, 8, 9, 10, 11, 12, 13, 14, 15}. We want
Create an Index: Divide the array into blocks and create an index that stores the
starting element and its corresponding index for each block. For this example, let's
8
9
10
11
12
13
14
15
Example
Consider a sorted array of integers: arr = {6, 7, 8, 9, 10, 11, 12, 13, 14, 15}. We want
10
11
12
13
14
15
Index
Key
12
15
Example
Consider a sorted array of integers: arr = {6, 7, 8, 9, 10, 11, 12, 13, 14, 15}. We want
to search for the element 8.
Compare the target element (8) with the elements in the index
8 is not less than index[0] (which is 6).
8 is less than index[1] (which is 9).
10
11
12
13
14
15
Index
Key
0
6
12
15
Example
Consider a sorted array of integers: arr = {6, 7, 8, 9, 10, 11, 12,
10
11
12
13
14
15
3
4
Index
Key
12
15
Q&A
What is the time complexity of Binary Search in the worst case?
A) O(1)
B) O(n)
C) O(log n)
D) O(n log n)
Q&A
Binary Search can only be applied to:
A) Unsorted arrays
B) Linked lists
C) Sorted arrays
D) Hash tables
Q&A
Which of the following is not a requirement for Binary Search to work correctly?
Q&A
Fibonacci Search divides the array using:
A) Middle element
B) Golden ratio
C) Fibonacci numbers
D) Prime numbers
Q&A
What is the worst-case time complexity of Fibonacci Search?
A) O(1)
B) O(n)
C) O(log n)
D) O(n log n)
Q&A
Indexed Sequential Search is a combination of:
Q&A
The index in Indexed Sequential Search typically stores:
A) Every element of the main list
D) All records
Sorting
Sorting is the operation of arranging the records of a table according to the key value of
A table or a file is an ordered sequence of records r[1], r[2], …, r[n], each containing a
key k[1], k[2], … , k[n]. This key is usually one of the fields of the entire record. The
table is said to be sorted on the key if i < j implies that k[i] precedes k[j] in some
with duplicate keys; that means, if for all records i and j is such that k[i] is equal to k[j]
and if r[i] precedes to r[j] in the unsorted table, then r[i] precedes to r[j] in the sorted
table too.
Bubble sort, selection sort, and insertion sort are the stable sort methods.
Efficiency
Each sorting method may be analysed depending on the amount of time necessary for
running the program and the amount of space required for the program.
The amount of time for running a program is proportional to the number of key
Passes
During the sorted process, the data is traversed many times.
Each traversal of the data is referred to as a sort pass.
Depending on the algorithm, the sort pass may traverse the whole list or just a section
of the list.
In addition, the characteristic of a sort pass is the placement of one or more elements in
a sorted list
Types of Sorting
Sorting algorithms are divided into two categories: internal and external
sorts.
Internal Sorting:- Any sort algorithm that uses main memory exclusively
External Sorting :- Any sort algorithm that uses external memory, such as
2. Insertion sort
3. Selection sort
4. Quick sort
5. Heap sort
6. Shell sort
7. Bucket sort
8. Radix sort
9. File sort
Bubble Sort
The bubble sort is the oldest and the simplest sort in use.
The bubble sort works by comparing each item in the list with the item next to it and
The algorithm repeats this process until it makes a pass all the way through the list
This causes larger values to ‘bubble’ to the end of the list while smaller values ‘sink’
Example
Example
Example-2
Example-2
second iteration, so on
(n - 1) + (n - 2) + (n - 3) + … + 1 = n(n - 1)/2
Insertion Sort
The insertion sort works just like its name suggests—it inserts each item into its proper
The simplest implementation of this requires two list structures: the source list and the
Insertion Sort
Let us consider a list L = {3, 6, 9, 14}. Given this sorted list, we need to insert a new
element 5 in it.
○
1. Compare the new element 5 and the last element 14
5. Insert 5 to get 3, 5, 6, 9, 14
Example
Example
Example
Example
Example-2
Algorithm
required in both the methods is approximately the same, that is, it is proportional to n2
(n - 1) + (n - 2) + …. + 1 = (n - 1) * n/2
which is O(n2).
Selection Sort
This algorithms construct the sorted sequence, one element at a time, by adding
At each step, the next element to be added to the sorted sequence is selected
Because the elements are added to the sorted sequence in order, they are always
This makes the selection sorting different from the insertion sorting.
In insertion sorting, the elements are added to the sorted sequence in an arbitrary
order.
Therefore, the position in the sorted sequence at which each subsequent element
is inserted is arbitrary.
Selection Sort
In the second step, swap the smallest element with the element at the first
position.
Then, find the next smallest element and swap with the element at the second
position.
Repeat these steps until all elements get arranged at proper positions.
Example
Example-2
comparisons are made. In general, for the ith pass, (n - i) comparisons are required
(n - 1) + (n - 2) + … + 1 = n(n -1)/2
Therefore, the number of comparisons for the selection sort is proportional to n2,
Quick Sort
Quick sort is based on the divide-and-conquer strategy.
This sort technique initially selects an element called as pivot that is near the middle of
the list to be sorted, and then the items on either side are moved so that the elements
on one side of pivot are smaller and on the other side are larger.
Now, the pivot is at the right position with respect to the sorted sequence.
These two steps, selecting the pivot and arranging the elements on either side of pivot,
are now applied recursively to both the halves of the list till the list size reduces to
one.
Quick Sort
Thus, the recursive algorithm consists of four steps
1. If the array size is 1, return immediately.
2. Pick an element in the array to serve as a ‘pivot’
3. Partition the array into two parts—one with elements smaller than the pivot and the
other with elements larger than the pivot by traversing from both the ends and
Example
Let us first find the elements larger than the pivot, that is, 13. In addition, let us find
the last element not larger than the pivot. These elements are in positions 2 and 9. Let
us swap those.
Example
Let us again start scanning from both the directions
Example
Let us repeat the steps to get the following sequence:
Here, the lower and upper bounds have crossed. So let us now swap the pivot-with
element 12.
Example
Here, we get two partitions as represented in the following sequence:
Recursively applying similar steps to each sub-list on the right and left side of the
pivot, we get,
Algorithm
The array is then divided into two parts each of size (n/2).
We assume that the array is divided into approximately one-half each time.
For each of these sub-arrays, (n/2) comparisons are made and four sub-arrays of size
time.
Virutual Lab
[Link]
[Link]
[Link]
[Link]
[Link]
Merge Sort
The most common algorithm used in external sorting is the merge sort.
Merging is the process of combining two or more sorted files into the third sorted file.
We can use a technique of merging two sorted lists.
Divide and conquer is a general algorithm design paradigm that is used for merge sort
Merge Sort
Merge sort has three steps to sort an input sequence S with n elements:
1. Divide—partition S into two sequences S1 and S2 of about n/2 elements each
2. Recur—recursively sort S1 and S2
3. Conquer—merge S1 and S2 into a sorted sequence
A file (or sub-file) is divided into two files, f1 and f2. These two files are then
Example
The operation of the algorithm on the list 8, 3, 2, 9, 7, 1, 5, 4 is illustrated as
Algorithm
Algorithm
Time Complexity
The worst case, Cmerge(n) = n − 1
Therefore the recurrence relation is
Hence, according to master theorem
–a = 2, b = 2, f(n) = n
Q&A
What is the key difference between internal and external sorting?
A. Internal sorting uses disk, external sorting uses RAM
Q&A
Which sorting algorithm is not efficient for large datasets due to its O(n²)
A. Merge Sort
B. Quick Sort
C. Insertion Sort
D. Heap Sort
Q&A
What is the average case time complexity of Bubble Sort?
A. O(n)
B. O(log n)
C. O(n log n)
D. O(n²)
Q&A
Which sorting algorithm repeatedly selects the minimum element and
A. Insertion Sort
B. Quick Sort
C. Selection Sort
D. Merge Sort
Q&A
What is the worst-case time complexity of Quick Sort?
A. O(n)
B. O(n log n)
C. O(n²)
D. O(log n)
Q&A
Merge Sort uses which algorithmic paradigm?
A. Backtracking
C. Greedy
D. Dynamic Programming
Q&A
Which sorting algorithm is stable and has a worst-case time complexity of
A. Quick Sort
B. Heap Sort
C. Merge Sort
D. Selection Sort
Q&A
External sorting is mainly required when:
A. Data is small