Input three numbers and display them in ascending order without using sort()
Expt. No.05
Page No.10
Sort three numbers without sort()
Aim
To write a Python program that accepts three numbers and displays them in ascending order without using sort() or sorted().
Concepts used
Algorithm
- Input three numbers a, b and c.
- If a > b, swap a and b.
- If b > c, swap b and c; now c holds the largest.
- If a > b, swap a and b again; now a holds the smallest.
- Display a, b and c.
Program
# Display three numbers in ascending order without sort() a = int(input("Enter the first number : "))b = int(input("Enter the second number: "))c = int(input("Enter the third number : ")) if a > b: a, b = b, a # swap using tuple assignmentif b > c: b, c = c, bif a > b: a, b = b, a print("In ascending order:", a, b, c)
A marked line continues the line above it. In your file, write it on the same line.
Output
Run 1
$ python sort_three_numbers.py
Enter the first number : 42
Enter the second number: 7
Enter the third number : 19
In ascending order: 7 19 42
Run 2
$ python sort_three_numbers.py
Enter the first number : 5
Enter the second number: 5
Enter the third number : 1
In ascending order: 1 5 5
✓ Printed by running this program, not typed by hand.
Result
42, 7 and 19 were displayed as 7 19 42, and 5, 5 and 1 as 1 5 5. Three compare-and-swap steps were enough to order three numbers, including when two of them are equal.
Viva voce: what the examiner may ask
01How does a, b = b, a swap two values?
The right side builds a tuple (b, a) first, then unpacks it into a and b. This is tuple assignment, so no third variable is needed.
02Why is the first comparison repeated at the end?
After the second swap, a new smaller value may have moved into b, so a and b must be compared again.
03How would you swap without tuple assignment?
Use a temporary variable: t = a, a = b, b = t.
Variations for the lab test
- Display the numbers in descending order.
- Swap using a temporary variable instead of tuple assignment.
- Display only the middle number.
! Common mistake Stopping after two comparisons: for 42, 7, 19 the result would be 7, 19, 42 by luck, but 5, 5, 1 would come out as 5, 1, 5.