BSF2205007 Muhammad Ramzan Algo 06 Complexity
BSF2205007 Muhammad Ramzan Algo 06 Complexity
RAMZAN
Roll No : Bsf2205007
Design and Analysis of Algorithm
ALGO NO:06.GIVEN AN ARRAY OF INTEGERS AND A TARGET SUM, FIND
TWO NUMBERS IN THE ARRAY THAT ADD UP TO THE TARGET. RETURN
THEIR INDICES.
CODE:
1. int main() {
2. int nums[] = {3,5,8,12};
3. int target = 13;
4. int n = sizeof(nums) / sizeof(nums[0]);
5. for (int i = 0; i < n; i++) {
6. for (int j = i + 1; j < n; j++) {
7. if (nums[i] + nums[j] == target) {
8. cout << "Indices: [" << i << ", " << j << "]" << endl;
9. return 0; } } }
10. cout << "No solution found." << endl;
11. return 0;
}
DRY RUN :
nums[] = {3, 5, 8, 12}
target = 13
n=4
Iteration 1:
i = 0, j = 1
Iteration 2
i = 0, j = 2
Iteration 3:
i = 0, j = 3
Iteration 4:
i = 1, j = 2
nums[i] + nums[j] = 5 + 8 = 13
Exit program
Output:Indices: [1, 2]
COMPLEXITY:
*Step 1: Initialization*
- `int nums[] = {3,5,8,12};` Complexity: O(1)
- `int target = 13;` Complexity: O(1)
- `int n = sizeof(nums) / sizeof(nums[0]);` Complexity: O(1)
*Step 5: Returning*