Skip to content
Exercises · Q4

Q.Write a program using user defined functions that accepts a List of numbers as an argument and finds its median. (Hint : Use bubble sort to sort the accepted list. If there are odd number of terms, the median is the center term. If there are even number of terms, add the two middle terms and divide by 2 get median)

Uttarakhand UbseTextbookSubjective· 3mImportance★★★★★
67% · 8/12 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

This program defines a function that takes a list of numbers, sorts it using bubble sort, and returns the median — the middle value for odd-length lists, or the average of the two middle values for even-length lists.

Why Bubble Sort for Median?

The median is a positional average — it depends entirely on the order of the data. Before you can pick the middle element(s), the list must be sorted. Bubble sort is a simple, comparison-based sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. Each full pass "bubbles" the largest unsorted element to its correct position at the end.

While not efficient for large datasets (O(n²)), bubble sort is perfect here because:

  • It's easy to implement and understand
  • The question explicitly asks for it
  • It works correctly for any list size
Watch out

A common mistake is to sort the list in place using Python's built-in list.sort() or sorted(). The question specifically requires you to implement bubble sort yourself — using the built-in sort defeats the purpose of the exercise.

The Program

def bubble_sort(numbers):
    """Sorts a list of numbers in ascending order using bubble sort."""
    n = len(numbers)
    # Outer loop: number of passes
    for i in range(n - 1):
        # Inner loop: compare adjacent elements
        # After each pass, the largest element is at the end, so we reduce the range
        for j in range(n - 1 - i):
            if numbers[j] > numbers[j + 1]:
                # Swap if out of order
                numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j]
    return numbers

def find_median(numbers):
    """Accepts a list of numbers and returns its median."""
    if not numbers:  # Handle empty list
        return None
    
    # Step 1: Sort the list using bubble sort
    sorted_numbers = bubble_sort(numbers.copy())  # Use copy to avoid modifying original
    
    # Step 2: Find the median
    n = len(sorted_numbers)
    mid = n // 2
    
    if n % 2 == 1:  # Odd number of elements
        median = sorted_numbers[mid]
    else:  # Even number of elements
        median = (sorted_numbers[mid - 1] + sorted_numbers[mid]) / 2
    
    return median

# Example usage
if __name__ == "__main__":
    # Test with odd number of elements
    list1 = [5, 2, 8, 1, 9]
    print(f"List: {list1}")
    print(f"Median: {find_median(list1)}")
    
    # Test with even number of elements
    list2 = [3, 7, 1, 4, 9, 6]
    print(f"\nList: {list2}")
    print(f"Median: {find_median(list2)}")
    
    # Test with single element
    list3 = [42]
    print(f"\nList: {list3}")
    print(f"Median: {find_median(list3)}")

Expected Output

List: [5, 2, 8, 1, 9]
Median: 5

List: [3, 7, 1, 4, 9, 6]
Median: 5.0

List: [42]
Median: 42

Key Lines Explained …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.