The Constitution Review Committee (CRC) has released an updated schedule for ...nservice241
Ad
DATA STRUCTURE AND COMPUTER ALGORITHMS LECTURE 1
1. Data Structure and Computer Programming
Course Code: CS 8238
By Betty Singano
2. Data structure an introduction:
•What is a data structure?
•A data structure is a way of organizing data in a
computer so that it can be used effectively.
•It is a storage that is used to store and organize data.
•It is a way of arranging data on a computer so that it
can be accessed and updated efficiently.
•A data structure is not only used for organizing the
data. It is also used for processing, retrieving and
storing data.
3. •Data structures are important because they allow us to
store and retrieve data efficiently, and to perform
various operations on data, such as sorting, searching
and inserting and deleting elements.
•There are different basic and advanced types of data
structures that are used in almost every program or
software system that has been developed. Because of
this we must have good knowledge of data structures.
•There are many different types of data structures, each
with its own advantages and disadvantages.
4. Some of the most common data structures include;
• Arrays: Arrays are a simple and efficient way to store a
collection of homogeneous elements.
• Linked lists: Linked lists are a flexible data structure that can
be used to store a collection of heterogeneous elements.
• Stacks: Stacks are a data structure that follows the last-in-
first-out (LIFO) principle.
• Queues: Queues are a data structure that follows the first-in-
first-out (FIFO) principle.
• Trees: Trees are a hierarchical data structure that can be
used to store and retrieve data efficiently.
• Graphs: Graphs are a non-hierarchical data structure that
can be used to represent relationships between entities.
6. Classification of Data Structure:
• Linear data structure:
Data structure in which data elements are arranged sequentially or linearly,
where each element is attached to its previous and next adjacent elements, is
called a linear data structure.
Examples of linear data structures are array, stack, queue, linked list, etc.
Static data structure:
Static Data Structures are data structures where the size is allocated at
the compile time. Hence, the maximum memory size is fixed and cannot
be changed. It is easier to access the elements in a static data structure.
An example of this data structure is an array.
Dynamic data structure:
Dynamic Data Structures are data structures where the size is allocated at
the run time. Hence, the maximum size is flexible and can be changed as per
requirements.
Examples of this data structure are queue, stack, etc.
7. •Non-linear data structure:
Data structures where data elements are not
placed sequentially or linearly are called non-
linear data structures.
In a non-linear data structure, we can’t traverse
all the elements in a single run only.
Examples of non-linear data structures are trees
and graphs.
8. Need of Data Structure:
Applications are becoming more complex and the amount of
data is increasing day by day, which may cause problems with
processing speed, searching data, handling multiple requests
etc.
• Data structure provides a way of organizing, managing and
storing data efficiently.
• With the help of data structure, the data items can be
traversed easily.
• Data structure provides efficiency, reusability and abstraction.
• It plays an important role in enhancing the performance of a
program because the main function of the program is to store
and retrieve the user’s data as fast as possible.
9. Why Learn Data Structure?
Data structure and algorithms are two of the most
important aspects of computer science.
Data structures allow us to organize and store data,
while algorithms allow us to process that data in a
meaningful way.
Learning data structure and algorithms will help you
become a better programmer. You will be able to write
code that is more efficient and more reliable. You will
also be able to solve problems more quickly and more
effectively.
10. Types of Data Structure:
There are 2 types of Data Structure:
• Primitive Data Structure
Primitive Data Structures directly operate according to the
machine instructions. These are the primitive data types. Data
types like int, char, float, double and pointer are primitive
data structures that can hold a single value.
• Non – Primitive Data Structure
Non-primitive data structures are complex data structures that
are derived from primitive data structures. Non – Primitive
data types are further divided into two categories.
Linear Data Structure
Non – Linear Data Structure
12. Data Structure Operations:
The common operations that can be performed on the data structures
are as follows:
• Searching – We can easily search/find for any data element in a data
structure.
• Sorting – We can arrange the elements either in ascending or
descending order.
• Insertion – We can insert/add new data elements in the data
structure.
• Deletion – We can delete/remove the data elements from the data
structure.
• Updation – We can update or replace the existing elements from the
data structure.
13. Benefits of using data structures:
• Efficiency:
Data structures allow us to store and retrieve data efficiently.
This is because they are designed to minimize the number of
operations required to perform these tasks.
• Flexibility:
Data structures are flexible and can be used to solve a wide
variety of problems.
• Reusability:
Data structures can be reused in different programs, which
can save us time and effort.
14. Advantages of Data Structure:
Data structures allow storing the information on hard disks.
An appropriate choice of ADT (Abstract Data Type) makes
the program more efficient.
Data Structures are necessary for designing efficient
algorithms.
It provides reusability and abstraction.
Using appropriate data structures can help programmers
save a good amount of time while performing operations
such as storage, retrieval or processing of data.
Manipulation of large amounts of data is easier.
15. Data Structure Applications:
Data structures are used in a wide variety of applications,
including operating systems, database systems, compilers
and web browsers.
For example,
• The operating system uses data structures to manage
memory, store files and schedule processes.
• Database systems use data structures to store and retrieve
data efficiently.
• Compilers use data structures to generate machine code
from source code.
• And web browsers use data structures to display web pages
and manage user interaction.
16. More Applications of data structure are used in:
1. Algorithms that analyze data (such as a data miner)
2. Algorithms that generate data (such as a random number generator)
3. Algorithms that compress and decompress data (such as a zip utility)
4. Algorithms that encrypt and decrypt data (such as a security system)
5. Software that manages files and directories (such as a file manager)
6. Software that renders graphics (such as a web browser or 3D rendering
software)
7. Organization of data in a computer’s memory
8. Representation of information in databases
9. Algorithms that search through data (such as a search engine)
10. Algorithms that manipulate data (such as a word processor)
17. Arrays:
What is an Arrays?
An array is a linear data structure that
collects/consist 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.
18. • An array is a linear data structure that stores a collection of
elements of the same data type in contiguous memory
locations.
• This means that all of the elements in an array are stored one
after the other in memory.
• Arrays are accessed using indices, which are integers that start
from 0 and go up to the length of the array minus 1.
• To access an element in an array, we simply use the array's
name followed by the index of the element we want to access.
For Example:
my_array = [1, 2, 3, 4, 5]
first_element = my_array [0]
The variable first_element will now contain the value 1.
19. Why Do You Need an Array in Data
Structures?
• Consider a class consists of a thousand students, and the class
advisor has to publish their results. If he/she had declared all
thousand variables individually, it would be challenging to manipulate
and maintain the data.
• If more students were to join, it would become more difficult to
declare all the variables and keep track of it. To overcome this
problem, arrays came into the picture.
20. Advantages of Arrays:
• Efficiency:
Arrays are very efficient for storing and retrieving data.
This is because they are stored in contiguous memory
locations, which means that the computer can access them
quickly and easily.
• Simplicity:
Arrays are a very simple data structure to understand and
use.
• Versatility:
Arrays can be used to store a wide variety of data types and
can be used to implement many different algorithms.
21. How arrays are used in real-world applications:
• Games:
Arrays are used to store game objects, such as characters, enemies, and
projectiles.
• Image processing:
Arrays are used to store images and to perform various image
processing operations, such as filtering and convolution.
• Machine learning:
Arrays are used to store data and to train and deploy machine learning
models.
• Scientific computing:
Arrays are used to store and manipulate data in scientific applications,
such as simulations and numerical analysis.
22. What Are the Types of Arrays?
There are majorly two types of arrays, they are:
• One-Dimensional Arrays:
25. In addition to these two main types of arrays, there are also a few other types of
arrays, such as:
• Jagged arrays:
Jagged arrays are a type of multi-dimensional array where each row can have a
different number of elements.
• Associative arrays:
Associative arrays are a type of array where the elements are accessed using
keys instead of indices.
One-dimensional arrays are the most common type of array and are used in a
wide variety of applications.
For example, one-dimensional arrays can be used to store the following:
• A list of names
• A list of numbers
• A list of characters
• A string of text
26. Multi-dimensional arrays are less common than one-
dimensional arrays, but they are still used in a variety of
applications.
For example, two-dimensional arrays can be used to store the
following:
• A matrix
• An image
• A table of data
Jagged arrays and associative arrays are more specialized types
of arrays that are used in specific applications.
For example, jagged arrays are often used to store data in a
tree structure, while associative arrays are often used to store
data in a database.
27. Array Declaration:
Arrays are typically declared with square brackets with the size of the
arrays as its argument.
Here is the syntax for arrays declaration:
• 1D Arrays: int arr[n];
• 2D Arrays: int arr[m][n];
• 3D Arrays: int arr[m][n][o];
28. Array Initialization:
Arrays can be initialized in four different ways:
• Method 1:
int a[6] = {2, 3, 5, 7, 11, 13};
• Method 2:
int arr[]= {2, 3, 5, 7, 11};
• Method 3:
int n;
scanf(“%d”,&n);
int arr[n];
for(int i=0;i<5;i++)
{
scanf(“%d”,&arr[i]);
}
35. Example program for array traversal:
#include<stdio.h>
int main()
{
int a[5] = {2, 3, 5, 7, 11};
for(int i=0;i<5;i++)
{
//traversing ith element in the array
printf(“%dn”,a[i]);
}
return 0;
}
37. Insertion in an Array:
Insertion in an array is the process of including/adding one or more
elements in an array.
Insertion of an element can be done:
• At the beginning
• At the end and
• At any given index of an array.
38. At the Beginning:
#include<stdio.h>
int main()
{
int array[10], n,i, item;
printf("Enter the size of array: ");
scanf("%d", &n);
printf("nEnter Elements in array: ");
for(i=0;i<n;i++)
{
scanf("%d", &array[i]);
}
39. printf("n enter the element at the beginning");
scanf("%d", &item);
n++;
for(i=n; i>1; i--)
{
array[i-1]=array[i-2];
}
array[0]=item;
printf("resultant array element");
for(i=0;i<n;i++)
{
printf("n%d", array[i]);
}
getch();
return 0;
}
43. At a Specific Position:
#include <stdio.h>
int main()
{
int array[100], pos, size, val;
printf("Enter size of the array:");
scanf("%d", &size);
printf("nEnter %d elementsn", size);
for (int i = 0; i < size; i++)
scanf("%d", &array[i]);
printf("Enter the insertion locationn");
44. scanf("%d", &pos);
printf("Enter the value to insertn");
scanf("%d", &val);
for (int i = size - 1; i >= pos - 1; i--)
array[i+1] = array[i];
array[pos-1] = val;
printf("Resultant array isn");
for (int i = 0; i <= size; i++)
printf("%dn", array[i]);
return 0;
}
46. Deletion in an Array:
Deletion of an element is the process of removing the desired element
and re-organizing it.
Deletion can be done in different ways:
• At the beginning
• At the end
• At a specified location.
47. At the Beginning:
#include<stdio.h>
int main()
{
int n,array[10];
printf("enter the size of an array");
scanf("%d" ,&n);
printf("enter elements in an array");
for(int i=0;i<n;i++)
scanf("%d", &array[i]);
50. At the End:
#include<stdio.h>
int main()
{
int n,array[10];
printf("enter the size of an array");
scanf("%d" ,&n);
printf("enter elements in an array");
for(int i=0;i<n;i++)
scanf("%d", &array[i]);
printf("nafter deletion array elements are");
for(int i=0;i<n-1;i++)
printf("n%d" , array[i]);
}
52. Searching for an Element:
The method of searching/finding for a specific value in an array is
known as searching.
There are two ways we can search in an array, they are:
• Linear search
• Binary search
53. Linear Search:
A linear search is the simplest approach employed to search
for an element in a data set.
It examines each element until it finds a match, starting at
the beginning of the data set, until the end.
The search is finished and terminated once the target
element is located. If it finds no match, the algorithm must
terminate its execution and return an appropriate result.
The linear search algorithm is easy to implement and efficient
in two scenarios:
• When the array contains lesser elements.
• When searching for a single element in an unordered array.
54. What Is a Linear Search Algorithm?
• Linear search, often known as sequential search, is the most basic
search technique.
• In this type of search, you go through the entire list and try to fetch a
match for a single element.
• If you find a match, then the address of the matching target element
is returned. On the other hand, if the element is not found, then it
returns a NULL value.
55. Step-by-step approach employed to perform Linear Search:
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.
Step 4: If both are not matched, compare the search element with the
next element in the array.
Step 5: In this step, repeat steps 3 and 4 until the search (Target)
element is compared with the last element of the array.
Step 6 : If the last element in the list does not match, the Linear Search
Function will be terminated, and the message "Element is not found"
will be displayed.
56. Algorithm of the Linear Search Algorithm:
Linear Search ( Array Arr, Value a ) // Arr is the name of the array, and a
is the searched element.
• Step 1: Set i to 0 // i is the index of an array which starts from 0
• Step 2: if i > n then go to step 7 // n is the number of elements in
array
• Step 3: if Arr[i] = a then go to step 6
• Step 4: Set i to i + 1
• Step 5: Goto step 2
• Step 6: Print element a found at index i and go to step 8
• Step 7: Print element not found
• Step 8: Exit
57. Sample Code:
#include <stdio.h>
int linear(int a[], int n, int x)
{
for (int i = 0; i < n; i++)
if (a[i] == x)
return i;
return -1;
}
int main(void)
{
int a[] = { 2, 3, 4, 10, 40 };
int x = 10;
58. int n = sizeof(a) / sizeof(a[0]);
// Function call
int result = linear(a, n, x);
if(result == -1)
{
printf("Element is not present in array");
}
else
{
printf("Element found at index: %d", result);
}
return 0;
}
60. Application of Linear Search Algorithm
The linear search algorithm has the following
applications:
•Linear search can be applied to both single-
dimensional and multi-dimensional arrays.
•Linear search is easy to implement and effective
when the array contains only a few elements.
•Linear Search is also efficient when the search is
performed to fetch a single search in an unordered-
List.
61. Binary Search:
•Binary searches are efficient algorithms based on the
concept of “divide and conquer” that improves the
search by recursively dividing the array in half until
you either find the element or the list gets narrowed
down to one piece that doesn’t match the needed
element.
•Binary searches work under the principle of using the
sorted information in the array to reduce the time
complexity to zero.
62. Binary search approach’s basic steps:
• Begin with an interval that covers the entire array
• If the search key value is less than the middle-interval item,
narrow the interval to that lower half. Otherwise, narrow the
interval to the upper half.
• Keep checking the chosen interval until either the value is
found or the interval’s empty
When to Use Binary Search:
Code testing, exams, technical recruiting interviews, code
challenges, library tasks, estimate maximum and minimum
sizes, etc.
63. Implementation of a Binary Search:
There are two forms of binary search implementation:
Iterative and Recursive Methods.
• The most significant difference between the two methods is the
Recursive Method has an O(logN) space complexity, while the
Iterative Method uses O (1). So, although the recursive version is
easier to implement, the iterative approach is more efficient.
• Iterative algorithms repeat a specific statement set a given number of
times. The algorithm uses looping statements (e.g., loop, while loop,
do-while loop) to repeat the same steps several times.
• On the other hand, recursive algorithms rely on a function that calls
itself repeatedly until it reaches the base condition (also called the
stopping condition).
64. Sorting in an array:
Sorting in an array is the process in which the array elements are
arranged in a user-defined order whether ascending or descending.
65. Example program:
#include <stdio.h>
void main()
{
int temp, size, array[100];
printf("Enter the size n");
scanf("%d", &size);
printf("Enter the numbers n");
for (int i = 0; i < size; ++i)
scanf("%d", &array[i]);
for (int i = 0; i < size; ++i)
{
for (int j = i + 1; j < size; ++j)
66. {
if (array[i] > array[j])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
} }
}
printf("sorted array:n");
for (int i = 0; i < size; ++i)
printf("%dn", array[i]);
}
68. Advantages of Arrays in Data Structures:
• Arrays store multiple elements of the same type with the same name.
• You can randomly access elements in the array using an index number.
• Array memory is predefined, so there is no extra memory loss.
• Arrays avoid memory overflow.
• 2D arrays can efficiently represent the tabular data.
Disadvantages of Arrays in Data Structures:
• The number of elements in an array should be predefined
• An array is static. It cannot alter its size after declaration.
• Insertion and deletion operation in an array is quite tricky as the array
stores elements in continuous form.
• Allocating excess memory than required may lead to memory wastage.