Advertisements
Advertisements
Question
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)
Solution
def bubblesort(numlist):
length = len(numlist)
for i in range( length - 1):
for j in range(0, n-1-i):
if numlist[j] > numlist[j+1]:
numlist[j], numlist[j+1] = numlist[j+1], numlist[j]
numbers = eval(input("Enter list using bracket : "))
bubblesort(numbers)
size = len(numbers)
mid = size // 2
if size % 2 == 0:
median = (numbers[mid] + numbers[mid+1]) / 2
else:
median = numbers[mid]
print("Given list in sorted orders : ")
print(numbers)
print("Median : ", median)
APPEARS IN
RELATED QUESTIONS
A list has 12 elements. How many passes will a bubble sort algorithm make to sort the list?
Which sorting technique sorts a given list of elements by repeatedly comparing the adjacent elements and swapping them if they are ordered?
Once an element is bubbled up it is:
How many loops does a bubble sort algorithm have?
What are the best and worst time complexity for bubble sort?
Which of the following is true for bubble sort of 16, 30, 14, 19?
How many swaps required to swap [60, 41, 20, 7] using bubble sort?
What is true for bubble sort?
Consider a list of 10 elements:
numList = [7, 11, 3, 10, 17, 23, 1, 4, 21, 5].
Display the partially sorted list after three complete passes of Bubble sort.
Identify the number of swaps required for sorting the following list using selection sort and bubble sort and identify which is the better sorting technique with respect to the number of comparisons.
List 1:
63 | 42 | 21 | 9 |