Assignment - 2 DAA LAB (0901CD231057)
Assignment - 2 DAA LAB (0901CD231057)
Output :-
Time Complexity:
Best Case: O(1) (when the target element is the first element in the array).
Worst Case: O(n) (when the target element is the last element in the array or is not
present at all).
Space Complexity:
The space complexity is O(1) because the algorithm uses a constant amount of extra
space regardless of the size of the input array. It only requires a few extra variables for
the index and target element.
if (arr[mid] == target)
return mid; // Element found, return index
else if (arr[mid] < target)
left = mid + 1; // Search in the right half
else
right = mid - 1; // Search in the left half
}
return -1; // Element not found
}
int main() {
int n, target;
// Input size of array
cout << "Enter the number of elements in the array: ";
cin >> n;
int arr[n];
// Output result
if (result != -1) {
cout << "Element found at index " << result << endl;
} else {
cout << "Element not found in the array." << endl;
}
return 0;
}
int main() {
int n, target;
int arr[n];
// Output result
if (result != -1) {
cout << "Element found at index " << result << endl;
} else {
cout << "Element not found in the array." << endl;
}
return 0;
}
Output :-
Time Complexity:
Best Case: O(1)(when the target element is the middle element).
Worst Case: O(log n) (as the problem size is halved at each step).
Space Complexity:
Iterative Version: O(1), as it uses a constant amount of space.
Recursive Version: O(log n), due to the recursive call stack that may go
as deep as log n levels, where n is the number of elements in the array.
struct Node {
int data;
Node *left, *right;
Node(int x) : data(x), left(nullptr), right(nullptr) {}
};
return root;
}
inorderTraversal(root->left);
cout << root->data << " ";
inorderTraversal(root->right);
}
int main() {
vector<int> inorder = {4, 2, 5, 1, 3, 6};
vector<int> preorder = {1, 2, 4, 5, 3, 6};
Output :-
Time Complexity:
o The time complexity is now O(n), where n is the number of nodes
in the tree. This improvement comes from using an unordered_map
to find the index of elements in the inorder traversal in O(1) time.
Space Complexity:
o The space complexity is O(n) due to:
o The recursion stack, which can go as deep as the height of the tree.
o The unordered_map that stores the indices of elements in the
inorder traversal.