Chapter 2
Chapter 2
Introduction
• A linear data structure is a type of data structure that stores the data linearly or
sequentially. In the linear data structure, data is arranged in such a way that one element
is adjacent to its previous and the next element. It includes the data at a single level such
that we can traverse all data into a single run.
• In computer science, an array is a linear data structure consisting of a collection of
elements (values or variables), of same memory size, each identified by at least one
array index or key.
The operations normally performed in linear data structure, are-
• Traversal: processing each element in the list.
• Search: find the location of the element with a given value.
• Insertion: adding a new element in the list.
• Deletion: removing an element from the list.
• Sorting: arranging the elements in some type of order.
• Merging: combining two lists into a single list.
Arrays
• An array is a collection of similar data elements stored at contiguous memory locations.
• Array is the simplest data structure where each data element can be accessed directly by
only using its index number.
• The elements of the array are referenced respectively by an index set consisting of
consecutive numbers.
• The elements of the array are stored respectively in successive memory locations.
• There are 3 common types of array.
• Indexed Array (a numeric index)
• Associative arrays (Arrays with named keys)
• Multidimensional arrays (Arrays containing one or more arrays)
• An array is a linear data structure that collects elements of the same data type and stores
them in contiguous and adjacent memory locations. Arrays work on an index system
starting from 0 to (n-1), where n is the size of the array.
• Arrays come in two main varieties – single-dimensional and multi-dimensional.
• Single-dimensional arrays store one type of data elements in a single row.
• Multi-dimensional arrays allow for the storage of multiple elements, each with their
unique index numbers.
This algorithm inserts an element ITEM into the Kth position in LA.
Step 1: [Initialise counter]
Set j = N;
Step 2: Repeat steps 3 and 4 while j>=K
Step 3: [Move jth element downward]
Set LA[j+1] = LA[j]
Step 4: [Decrease counter]
Set j=j-1
[End of Step 2 loop]
Step 5: [Insert element]
Set LA[K] = ITEM
Step 6: [Reset N]
Set N = N+1
Step 7: Exit
• The inner loop will run from j = 0 to j < n – i – 1. It is because, after each iteration of
the outer loop, one element at the end (or at the start if the order is decreasing order)
will be in its right place so we can leave it as it is.
• This process will be repeated till the conditions of the loop are satisfied.
For decreasing order,
SKIP
• The inner loop will run from j = i to j < n – 1.
• We will compare the elements as arr[ j ] < arr[ j + 1 ].
• Everything else will be the same.
Bubble Sort algorithm
• The bubble sort algorithm is a reliable sorting algorithm. To calculate the complexity
of the bubble sort algorithm, it is useful to determine how many comparisons each
loop performs.
• This algorithm has a worst-case time complexity of O(n2). The bubble sort has a space
complexity of O(1). The number of swaps in bubble sort equals the number of
inversion pairs in the given array.
• The worst situation for bubble sort is when the list's smallest element is in the last
position. In this situation, the smallest element will move down one place on each pass
through the list, meaning that the sort will need to make the maximum number of
passes through the list, namely n - 1.
• While bubble sort is a simple and easy-to-understand algorithm, it's not the most
efficient. In fact, it has a worst-case time complexity of O(n^2), which means that it's
not a good choice for sorting very large lists.
Searching in a Linear Array
• To search in an array of structs in C, iterate through each element of the array and
compare the search key with the relevant field of each struct.
• The basic steps involved in searching is-
• Step 1: First, read the search element (Target element) in the array.
• Step 2: In the second step compare the search element with the first element in the
array.
• Step 3: If both are matched, display "Target element is found" and terminate the Linear
Search function.
Searching in a Linear Array
• In C, Linear Search involves traversing a list or array sequentially to see if an
entry is there. The goal is to begin traversing the array and compare items of the
array one by one, starting with the first element, until a match is discovered or the
array's end is reached.
• We can implement linear search in C to check if the given element is present in
both random access and sequential access data structures such as arrays, linked
lists, trees, etc.
• Linear Search compares each element of the list with the key till the element is
found or we reach the end of the list.
The algorithm for linear search can be broken down into the following steps:
• Start: Begin at the first element of the collection of elements.
• Compare: Compare the current element with the desired element.
• Found: If the current element is equal to the desired element, return true or index
to the current element.
• Move: Otherwise, move to the next element in the collection.
• Repeat: Repeat steps 2-4 until we have reached the end of collection.
• Not found: If the end of the collection is reached without finding the desired
element, return that the desired element is not in the array.
Algorithm for Linear Search
• The algorithm finds the location LOC of ITEM in a given information.
• 1. [insert ITEM at the end of the DATA] Set DATA[N+1] = ITEM
• 2. [Initialize counter] Set LOC = 1
• 3. [Search for ITEM] Repeat while DATA[LOC] = ITEM
Set LOC = LOC + 1
[End of the Loop]
4. [Successful] if LOC = N + 1, then Set LOC = 0
5. Exit.
How Does Linear Search Algorithm Work
• In Linear Search Algorithm,
• Every element is considered as a potential match for the key and checked for the
same.
• If any element is found equal to the key, the search is successful and the index of
that element is returned.
• If no element is found equal to the key, the search yields “No match found”.
Binary search
• Binary search is a search algorithm used to find the position of a target value within
a sorted array. It works by repeatedly dividing the search interval in half until the
target value is found or the interval is empty. The search interval is halved by
comparing the target element with the middle value of the search space.
Conditions to apply Binary Search Algorithm in a Data Structure
• To apply Binary Search algorithm:
• The data structure must be sorted.
• Access to any element of the data structure takes constant time.
• Compare the middle element of the search space with the key.
• If the key is found at middle element, the process is terminated.
• If the key is not found at middle element, choose which half will be used as the
next search space.
• If the key is smaller than the middle element, then the left side is used for next
search.
• If the key is larger than the middle element, then the right side is used for next
search.
• This process is continued until the key is found or the total search space is
exhausted.
Binary search
• [Initialize segment variable]
1.Set BEG = LB, END = UB and MID = INT((BEG + End)/2)
2. Repeat step 3 & 4 while BEG<=END and DATA[MID] ≠ ITEM
3. If ITEM < DATA [MID], then
Set END = MID =1
else
Set BEG = MID ≠ 1
[End of if structure]
4. Set MID = INT((BEG + END)/2)
[End of step 2]
5. If DATA[MID] = ITEM. Then
Set LOC = MID
else
Set LOC = NULL
[End of if structure]
6. Exit.
Complexity Analysis of Binary Search Algorithm:
• Time Complexity
• Best Case: O(1)
• Average Case: O(log N)
• Worst Case: O(log N)
• Auxiliary Space: O(1), If the recursive call stack is considered then the auxiliary
space will be O(logN).
Applications of Binary Search Algorithm:
• 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.
• It can be used for searching in computer graphics such as algorithms for ray
tracing or texture mapping.
• It can be used for searching a database.
Advantages of Binary Search
• Binary search is faster than linear search, especially for large arrays.
• More efficient than other searching algorithms with a similar time complexity,
such as interpolation search or exponential search.
• 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.
Disadvantages of Binary Search
• The array should be sorted.
• Binary search requires that the data structure being searched be stored in
contiguous memory locations.
Binary search requires that the elements of the array be comparable, meaning that they must
be able to be ordered
Multidimensional Array
• A multi-dimensional array is an array that has more than one dimension. It is an array
of arrays; an array that has multiple levels. The simplest multi-dimensional array is the
2D array, or two-dimensional array.
• A multi-dimensional array can be termed as an array of arrays that stores homogeneous
data in tabular form. Data in multidimensional arrays is generally stored in row-major
order in the memory.
• Let's look at a practical example of using multidimensional arrays in C. Suppose we
want to create a program that stores the grades of 5 students in 4 different subjects. We
can use a 2-dimensional array to store this data, where each row represents a student,
and each column represents a subject.
Multidimensional Array
• The general form of declaring N-dimensional arrays is shown below.
• data_type: Type of data to be stored in the array.
• array_name: Name of the array.
• size1, size2,…, sizeN: Size of each dimension.
• Example:
Two dimensional array: int two_d[10][20];
Three dimensional array: int three_d[10][20][30];
2D
A two-dimensional array or 2D array in C is the simplest form of the multidimensional
array. We can visualize a two-dimensional array as an array of one-dimensional arrays
arranged one over another forming a table with ‘x’ rows and ‘y’ columns where the row
number ranges from 0 to (x-1) and the column number ranges from 0 to (y-1).
• The various ways in which a 2D array can be initialized are as follows:
1. Using Initializer List
int x[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 , 10 , 11}
2. Using Loops
int x[3][4] = {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}};
How 2D Arrays are Stored in the Memory
• The elements of the 2-D array have to be stored contiguously in memory. As the
computers have linear memory addresses, the 2-D arrays must be linearized so as
to enable their storage. There are two ways to achieve linearization of array
elements:
• Row-major- The linearization technique stores firstly the first row of the array,
then the second row of the array, then the third row, and so on. (i.e. elements are
stored row-wise. Rows are listed on the basis of columns)
• Column-major– This linearization technique stores first the first column, then the
second column, then the third column, and so on i.e. (elements are stored column-
wise. Columns are listed on the basis of rows)
• The computer does not keep track of the addresses of all the elements of the array
but does keep track of the Base Address (starting address of the very first element)
and calculates the addresses of the elements when required.
3D
• A Three Dimensional Array or 3D array in C is a collection of two-dimensional
arrays. It can be visualized as multiple 2D arrays stacked on top of each other.
• We can declare a 3D array with x 2D arrays each having y rows and z columns using
the syntax shown below.
• Syntax: data_type array_name[x][y][z];
• array_name: name of the array
• x: Number of 2D arrays.
• y: Number of rows in each 2D array.
• z: Number of columns in each 2D array.
• Initialization of Three-Dimensional Array in C
• Initialization in a 3D array is the same as that of 2D arrays. The difference is as
the number of dimensions increases so the number of nested braces will also
increase. A 3D array in C can be initialized by using:
• Initializer List
int x[2][3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
19, 20, 21, 22, 23};
• Loops
int x[2][3][4] =
{
{ {0,1,2,3}, {4,5,6,7}, {8,9,10,11} },
{ {12,13,14,15}, {16,17,18,19}, {20,21,22,23} }
};
Pointers in Array
• Pointers are one of the core components of the C programming language. A pointer can
be used to store the memory address of other variables, functions, or even other pointers.
The use of pointers allows low-level memory access, dynamic memory allocation, and
many other functionality in C.
• A pointer is defined as a derived data type that can store the address of other C variables
or a memory location. We can access and manipulate the data stored in that memory
location using pointers.
• In C, a pointer array is a homogeneous collection of indexed pointer variables that are
references to a memory location. It is generally used in C Programming when we want
to point at multiple memory locations of a similar data type in our C program. We can
access the data by dereferencing the pointer pointing to it.