Assignment 1
Assignment 1
Index number:052441340027
Course code:BDS 111
Assignment 1
b. Data structure:A data structure is a way to organize, store, and manage data
in a computer so that it can be efficiently accessed, modified, and manipulated. It
provides a framework for storing and retrieving data, and enables efficient
operations such as insertion, deletion, searching, and sorting.
# Initial list
nums = [10, 20, 30, 40, 50]
# a. Insert 25 at index 2
nums.insert(2, 25)
print("After inserting 25 at index 2:", nums)
After inserting 25 at index 2: [10, 20, 25, 30, 40, 50]
A linked list and an array are both data structures used to store collections of
elements, but they differ in how they store and manage the elements:
Array
- Stores elements in contiguous memory locations.
- Each element is identified by an index or subscript.
- Elements are accessed using their index, allowing for fast and efficient access.
- Insertion or deletion of elements can be slow, as it requires shifting all
subsequent elements.
Linked List
- Stores elements as separate objects, each containing a value and a reference
(i.e., a "link") to the next element.
- Elements are accessed by traversing the list from the beginning, following the
links between elements.
- Insertion or deletion of elements is faster, as only the affected elements and
their links need to be updated.
In summary, arrays offer fast access to elements but slow insertion/deletion, while
linked lists offer fast insertion/deletion but slower access to elements. The choice
between the two depends on the specific requirements of the application.
Here are some examples of scenarios where each data structure would be preferred:
Arrays:
1. Fixed-size data: When the number of elements is fixed and known in advance,
arrays are a good choice. For example, a game with a fixed number of players.
2. Fast access: When fast access to elements is critical, arrays are preferred. For
example, in a database query where you need to quickly retrieve data.
3. Cache efficiency: Arrays are cache-friendly, making them suitable for
applications where cache efficiency is important, such as in scientific simulations.
Linked Lists:
def sum_elements(arr):
total = 0
for i in arr:
total += i
return total
Analysis:
The function iterates through each element of the array arr once.
The operation total += i is a constant-time operation (O(1)) for each iteration.
If the array has n elements, the loop runs n times.
5. Python Program to Find Maximum and Minimum in an Array Without Built-In Functions
Here’s the program:
python code:
def find_min_max(arr):
if not arr: # Check if the array is empty
return None, None
# Initialize min and max with the first element of the array
min_element = arr[0]
max_element = arr[0]
makefile
Minimum: -5
Maximum: 9
Time Complexity: O(n), as the function iterates through the array once.
Space Complexity: O(1), as no additional