There are multiple
algorithms for a given problem. Assume we need to write a program to
"swap the two numbers," and we write two programs in C to do so. We
are only looking at time complexity.
Code 1 - Swap(A,B,C)
1. int main()
2. {
3. int A, B, C;
4. printf(“Enter the
first number : “);
5. scanf(“%d”,
&A);
6. printf(“Enter the second
number : “);
7. scanf(“%d”, &B);
8. C = A;
9. A = B;
10. B = C;
11. printf(“After
Swapping A : ”, A);
12. printf(“After
Swapping B : “, B);
Code 2 – Swap(A, B)
1. int main()
2. {
3. int A, B;
4. printf(“Enter two
numbers : “);
5. scanf(“%d %d”,
&A, &B);
6. A = A*B;
7. B = A/B;
8. A = A/B;
9. printf(“After
Swapping A : ”, A);
10. printf(“After
Swapping B : “, B);
As a result, code 1
swaps by using a variable C. The logic behind code 1 is that A and B are two
numbers that we swap by putting C variable value equals A variable value and A
variable value equals B variable value. Now we will set the value of B variable
to the value of C variable. As a result, A will become B, and B will become A.
This program includes
no complex logic, only simple common sense. However, the space we used is a
“int” data type variable.
In code 2, we swap
values by not taking up space as we solve the problem internally. There are two
variables A and B, and let's say A is equal to 3 and B is equal to 5. We now
multiply both variables and pass the result to variable A. A = 15 and B = 5 as
previously stated. In the following step, we change the value of B to be equal
to A/B, resulting in a new value of B of 3. Now we must change the value of the
A variable, which is equal to A/B, which equals 15/3 (the new value of B is 3),
which equals 5. We swapped the values. B = 3 and A = 5.
The computer only
understands addition. So, in code 2, if we multiply A and B, we must add A value
to B times, which equals 5 + 5 + 5, and division requires more complex
operations and time. The time complexity of code 2 will be greater than that of
code 1.
If we consider space
complexity, code 2 is a good algorithm because it does not require more variables;
however, if we consider time complexity, code 1 will be executed in less time
than code 2.
0 Comments