0% found this document useful (0 votes)
12 views14 pages

Chapter 2

Chapter 2 discusses linear data structures, focusing on arrays, their operations, and algorithms for insertion, deletion, sorting, and searching. It explains the characteristics of arrays, including single-dimensional and multi-dimensional types, and details algorithms like bubble sort and linear search, along with their complexities. The chapter also contrasts linear search with binary search, highlighting the conditions for their application and their respective advantages and disadvantages.

Uploaded by

lap use
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)
12 views14 pages

Chapter 2

Chapter 2 discusses linear data structures, focusing on arrays, their operations, and algorithms for insertion, deletion, sorting, and searching. It explains the characteristics of arrays, including single-dimensional and multi-dimensional types, and details algorithms like bubble sort and linear search, along with their complexities. The chapter also contrasts linear search with binary search, highlighting the conditions for their application and their respective advantages and disadvantages.

Uploaded by

lap use
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/ 14

Chapter – 2 ( Array, Records & Pointers)

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.

Representation of an Array in Memory


Let LA be a linear array in the memory of the computer. To recall the memory of the computer
simply addressed by the notation as-
LOC(LA[K]) = address of the element LA[K] of the array LA

Traversing a Linear Array


• Traversing a linear array involves systematically visiting each element, unveiling the
contents stored in this straightforward but crucial data structure.
• If LA is a linear array with lower bound LB and upper bound UB.
1. [Initialize counter] Set K = LB
2. Repeat step 3 and 4 while K <= UB
3. [Visit element] Apply Process to LA[K]
4. [Increase counter] Set K =K+1
[End of step 2 loop]
5. Exit.

Inserting into a Linear Array


1. First of all, we have to check that whether there is a room(space) available or not.
2. Where the element to insert(as mentioned like begin, end or at any given index).
3. If we insert an element in the middle location then we first move the last element into
the next location(downward) and like wise we shift the elements till the space is obtain
to insert new element.
• Insert(LA,N,K,ITEM) where
LA =Linear array
N =Number of elements
K =the position where element to insert
ITEM = the value to insert in the position K.

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

Deleting an element from a Linear Array


• Delete an element from a particular location. When we want to delete the last element
in the array, we simple decrease the length of an array but if we want to delete the
middle element into the array then:
1. First we have to find the position of the element.
2. Move the elements to upward.
Delete(LA, N, K, ITEM) where
LA = Linear array
N = Number of elements
K = the position where element to delete
ITEM = the element in the position K
In the algorithm, LA is the linear array with N elements and K is the integer such that K≤N.
In this it deletes the Kth element from the linear array[LA].
Step 1: Set ITEM = LA[K]
Step 2: Repeat for J = K to N-1
[Move 'J+1' element to upward]
set LA[J] = LA[J+1]
[End of loop]
Step 3: Rest the number 'N' of LA.
Set N = N-1
Step 4: Exit
How to Sort an Array
Sorting an array refers to the operation of rearranging the elements of an array A so they are
in increasing order.
Let, A be the list of n numbers
A[1] < A [2] < A [3] < … … … < A[N]
For example. Suppose A originally has a list as
8, 4, 19, 2, 7, 13, 5, 20
After sorting. A is the list
2, 4, 5, 7, 8, 13, 19, 20
This above example is for arranging an array in increasing order. Sorting may also mean
arranging numerical data in decreasing order.
Algorithm for Sort an Array Elements
1. START.
2. INITIALIZE arr[i] ={5, 2, 8, 7, 1}.
3. SET temp =0.
4. length= sizeof(arr)/sizeof(arr[0])
5. PRINT "Elements of Original Array"
6. SET i=0. REPEAT STEP 7 and STEP 8 UNTIL i<length.
7. PRINT arr[i]
8. i=i+1.
9. Exit

Bubble Sort Algorithm


• Bubble sort is a sorting algorithm that starts from the first element of an array and
compares it with the second element. If the first element is greater than the second, we
swap them. It continues this process until the end of the array, with the largest elements
“bubbling” to the top.
How does Bubble Sort works in C
1. Starts from the first index: arr[0] and compares the first and second element: arr[0] and
arr[1]
2. If arr[0] is greater than arr[1], they are swapped.
3. Similarly, if arr[1] is greater than arr[2], they are swapped.
4. The above process continues until the last element arr[n-1]
How to sort data of the list using bubble sort in C
• Run two loops nested in one another.
The outer loop will run from i = 0 to i < n – 1, where n is the number of elements in
the list.

• 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.

• In the inner loop, we will check if the arr[ j ] > arr[ j + 1 ].


• If it’s true, then we will swap places of these elements.
• If false, we will continue to the next iteration.

• 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”.

Time and Space Complexity of Linear Search


• Time Complexity
• Best Case: In the best case, the key might be present at the first index. So the best
case complexity is O(1).
• Worst Case: In the worst case, the key might be present at the last index i.e.,
opposite to the end from which the search has started in the list. So the worst-case
complexity is O(N) where N is the size of the list.
Applications of Linear Search
• Unsorted Lists: When we have an unsorted array or list, linear search is most
commonly used to find any element in the collection.
• Small Data Sets: Linear Search is preferred over binary search when we have small
data sets with
• Searching Linked Lists: In linked list implementations, linear search is commonly
used to find elements within the list. Each node is checked sequentially until the
desired element is found.
• Simple Implementation: Linear Search is much easier to understand and implement
as compared to Binary Search or Ternary Search.
Advantages of Linear Search
• 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.
Disadvantages 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 arrays.

When to use Linear Search


• When we are dealing with a small dataset.
• When you are searching for a dataset stored in contiguous memory.

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];

Size of Multidimensional Arrays


• The total number of elements that can be stored in a multidimensional array can
be calculated by multiplying the size of all the dimensions.
For example
• The array int x[10][20] can store total (10*20) = 200 elements.
• Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.
• To get the size of the array in bytes, we multiply the size of a single element with
the total number of elements in the array.

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.

pointer_type *array_name [array_size];


Here,
• pointer_type: Type of data the pointer is pointing to.
• array_name: Name of the array of pointers.
• array_size: Size of the array of pointers.
An array of pointers is useful in a wide range of cases. Some of these applications are listed
below:
• It is most commonly used to store multiple strings.
• It is also used to implement LinkedHashMap in C and also in the Chaining technique of
collision resolving in Hashing.
• It is used in sorting algorithms like bucket sort.
• It can be used with any pointer type so it is useful when we have separate declarations
of multiple entities and we want to store them in a single place.
Disadvantages
The array of pointers also has its fair share of disadvantages and should be used when the
advantages outweigh the disadvantages. Some of the disadvantages of the array of pointers
are:
• Higher Memory Consumption: An array of pointers requires more memory as
compared to plain arrays because of the additional space required to store pointers.
• Complexity: An array of pointers might be complex to use as compared to a simple
array.
• Prone to Bugs: As we use pointers, all the bugs associated with pointers come with
it so we need to handle them carefully.
Array Pointers
int myNumbers[4] = int myNumbers[4] = {25, 50, 75, 100};
{25, 50, 75, 100};
int i; int i;
for (i = 0; i < 4; i++)
{ for (i = 0; i < 4; i++)
printf("%d\n", myNumbers[i]); {
} printf("%p\n", &myNumbers[i]);
}

Records and Record Structures


• A record is a collection of related data items, each of which is called a field or attribute
and a file is a collection of similar records.
• Records differ from a linear array in the following ways
1. A record may be a collection of nonhomogeneous data i.e. the data items in a record
may have different data types.
2. The data items in a record are indexed by attribute names, so there may not be a
natural ordering of its elements.
Under the relationship of group item to subitem, the data items in a record form a
hierarchical structure which can be described by means of level numbers.

You might also like