Javatpoint Logo
Javatpoint Logo

Middle of three numbers using minimum comparisons in Python

In many Competitive exams, we encounter problems in finding the middle number. It is also important to consider the constraints given in the problem, like minimum comparisons. Let's see different solutions to the problem.

1. Traditional Approach

In the traditional approach, using mathematical calculation, the middle element will be found. In the first step, the total of three numbers is calculated, and then the maximum and minimum values from the list are retrieved using the max and min functions. Now, the middle element is calculated by subtracting min and max from the total.

The approach is efficient in terms of the readability of the code and the complexity of computation.

Code

Output:

Approach 5 Output:
5
3
7

Time Complexity : O(1)

Space Complexity: O(1)

2. Conditional Statements

If else statements are used in this approach to compare the numbers and then find the middle element. This approach is less efficient.

Code

Output:

Approach 5 Output:
5
3
7

Time Complexity : O(1)

Space Complexity: O(1)

3. Sorting

In this approach, all the elements are sorted according to ascending order, and then the middle element is found. With the goal of finding the middle value, this is not efficient as the computation complexity is very low for this approach.

Code

Output:

Approach 5 Output:
5
3
7

Time Complexity : O(1)

Space Complexity: O(1)

4. Bitwise Operators

Bitwise operators are used for the comparison, and then the middle element is found. These operators are not commonly used for these tasks, but for minimum comparisons, bitwise operators are a better choice. This approach is efficient but not readable.

Code

Output:

Approach 5 Output:
5
3
7

Time Complexity : O(1)

Space Complexity: O(1)

5. Ternary Operator

Ternary operator 'x if condition else y' is used to find the middle element. This is used for a better readable and compact solution. The approach is efficient in terms of the readability of the code and the complexity of computation.

Code

Output:

Approach 5 Output:
5
3
7

Time Complexity : O(1)

Space Complexity: O(1)







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA