c que 2
c que 2
Types
of DS?
DS:- Data structure 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.
Non-linear data structures are further divided into graph and tree based data
structures.
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("The maximum element is %d\n", findMax(arr, n));
return 0;
}
Analysis
1. Initialization: The variable max is initialized to the first element of the array. This step
takes constant time, O(1).
2. Loop: The loop runs n-1 times (from i = 1 to i = n-1). For each iteration, a
comparison is made, and possibly an assignment if a new maximum is found. The loop thus
takes linear time, O(n).
3. Return Statement: The final value of max is returned, which again takes constant time,
O(1).
Combining these steps, the overall time complexity of the function is determined by the loop, which
is the dominant factor. Therefore, the time complexity of findMax function is O(n).
Complexity of Algorithms
Complexity measures the efficiency of an algorithm in terms of time and space as the input size
increases. The two main types are:
1. Time Complexity: Measures how the running time of an algorithm increases with the input
size.
• O(1): Constant time (e.g., array access)
• O(log n): Logarithmic time (e.g., binary search)
• O(n): Linear time (e.g., iterating through an array)
• O(n log n): Linearithmic time (e.g., merge sort)
• O(n^2): Quadratic time (e.g., bubble sort)
• O(2^n): Exponential time (e.g., brute force for TSP)
• O(n!): Factorial time (e.g., brute force for TSP)
2. Space Complexity: Measures how the memory usage of an algorithm increases with the
input size.
• O(1): Constant space (e.g., using a few variables)
• O(n): Linear space (e.g., storing an array of size nn)
• O(n^2): Quadratic space (e.g., using a 2D array of size n×nn \times n)
Example
Consider a linear search algorithm in an unsorted array:
1. Best Case (Ω(1)): The element is found at the first position.
2. Worst Case (O(n)): The element is found at the last position or not found at all.
3. Average Case (Θ(n/2)): On average, the element is found in the middle.