Sorting

This page contains the NCERT Computer Science class 12 chapter 5 Sorting. You can find the solutions for the chapter 5 of NCERT class 12 Computer Science Exercise. So is the case if you are looking for NCERT class 12 Computer Science related topic Sorting questions and answers for the Exercise
Exercise
Question 1
1. 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
Answer 1
Bubble Sort (Ascending) — After each pass
In bubble sort, we repeatedly compare adjacent elements and do swapping if they are unordered. Each full scan is a pass.
Pass
List after the pass
Initial
[7, 11, 3, 10, 17, 23, 1, 4, 21, 5]
Pass 1
[7, 3, 10, 11, 17, 1, 4, 21, 5, 23]
Pass 2
[3, 7, 10, 11, 1, 4, 17, 5, 21, 23]
Pass 3
[3, 7, 10, 1, 4, 11, 5, 17, 21, 23]
Partially sorted list after 3 passes: [3, 7, 10, 1, 4, 11, 5, 17, 21, 23]
Program:
# Bubble sort: show list after 3 complete passes
numList = [7, 11, 3, 10, 17, 23, 1, 4, 21, 5]  # list to be sorted

# i = pass number (0 to 2)
for i in range(3):
    # j scans adjacent elements for this pass
    for j in range(0, len(numList) - 1 - i):
        # swap if left element is larger than right element
        if numList[j] > numList[j + 1]:
            numList[j], numList[j + 1] = numList[j + 1], numList[j]  # swap adjacent values
    # show list after each complete pass
    print("After pass", i + 1, ":", numList)
Sample Output:
After pass 1 : [7, 3, 10, 11, 17, 1, 4, 21, 5, 23]
After pass 2 : [3, 7, 10, 11, 1, 4, 17, 5, 21, 23]
After pass 3 : [3, 7, 10, 1, 4, 11, 5, 17, 21, 23]
Question 2
2. 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
Answer 2
(A) Selection Sort
Selection sort makes passes and selects the smallest element from the unsorted list and swaps it with the leftmost unsorted element.
List: [63, 42, 21, 9]
Pass 1: smallest is 9 → swap with 63 → 1 swap
Pass 2: remaining [42, 21, 63], smallest is 21 → swap with 42 → 1 swap
Pass 3: remaining [42, 63], already in order → 0 swap
Total swaps (Selection Sort) = 2
(B) Bubble Sort
Bubble sort swaps adjacent elements whenever needed.
For [63, 42, 21, 9] (reverse order), swaps will be:
Pass 1: 3 swaps
Pass 2: 2 swaps
Pass 3: 1 swap
Total swaps (Bubble Sort) = 6
(C) Which is better w.r.t comparisons?
Basic Bubble sort comparisons for 4 elements = 3 + 2 + 1 = 6
Selection sort comparisons for 4 elements = 3 + 2 + 1 = 6 (finding minimum each pass)
Both have the same number of comparisons (= 6) for this list.
So neither is better than the other in comparisons here (they are equal).
ℹ️ Note: Note that we’re making a judging based on the number of comparisons and not based on the number of swaps. The question requires us to identify the number of swaps. But it is asking us to decide which is better with resppect to the number of comparisons.
Program:
# Compare swaps and comparisons for Selection Sort vs Bubble Sort
numList = [63, 42, 21, 9]  # list to be sorted

def selection_counts(arr):
    a = arr[:]  # working copy of list
    swaps = 0   # counts swaps
    comps = 0   # counts comparisons
    for i in range(len(a) - 1):
        min_idx = i  # index of smallest element in unsorted part
        for j in range(i + 1, len(a)):
            comps += 1  # compare a[j] with current minimum
            if a[j] < a[min_idx]:
                min_idx = j  # update minimum index
        # swap smallest found into correct position
        if min_idx != i:
            a[i], a[min_idx] = a[min_idx], a[i]
            swaps += 1
    return swaps, comps

def bubble_counts(arr):
    a = arr[:]  # working copy of list
    swaps = 0   # counts swaps
    comps = 0   # counts comparisons
    for i in range(len(a) - 1):
        # compare adjacent elements in remaining unsorted range
        for j in range(0, len(a) - 1 - i):
            comps += 1
            if a[j] > a[j + 1]:
                a[j], a[j + 1] = a[j + 1], a[j]  # swap out-of-order pair
                swaps += 1
    return swaps, comps

sel_swaps, sel_comps = selection_counts(numList)  # selection sort metrics
bub_swaps, bub_comps = bubble_counts(numList)     # bubble sort metrics

print("Selection Sort -> swaps:", sel_swaps, ", comparisons:", sel_comps)
print("Bubble Sort    -> swaps:", bub_swaps, ", comparisons:", bub_comps)
print("Better w.r.t comparisons:", "Both (equal)")
print("Better w.r.t swaps:", "Selection Sort")
Sample Output:
Selection Sort -> swaps: 2 , comparisons: 6
Bubble Sort    -> swaps: 6 , comparisons: 6
Better w.r.t comparisons: Both (equal)
Better w.r.t swaps: Selection Sort
Question 3
3. Consider the following lists:
List 1:
2
3
5
7
11
List 2:
11
7
5
3
2
If the lists are sorted using Insertion sort then which of the lists List 1 or List 2 will make the minimum number of comparisons? Justify using diagrammatic representation.
Answer 3
The diagrammatic representation of the insertion sort for List 1 and List 2 is shown below:
Indicates element(s) in sorted listInsertion Sort for List 1List 1:Original list element (index 1)Original list element (index 2)Original list element (index 3)Original list element (index 4)Original list element (index 5)235711Comparison in Pass 1Pass 1 (before): sorted part (size 1)Pass 1 (before): unsorted partPass 1 (before): unsorted partPass 1 (before): unsorted partPass 1 (before): unsorted part235711Pass 1 (after): sorted part (size 2)Pass 1 (after): sorted part (size 2)Pass 1 (after): unsorted partPass 1 (after): unsorted partPass 1 (after): unsorted part235711No ChangeComparison in Pass 2Pass 2 (before): sorted part (size 2)Pass 2 (before): sorted part (size 2)Pass 2 (before): unsorted partPass 2 (before): unsorted partPass 2 (before): unsorted part235711Pass 2 (after): sorted part (size 3)Pass 2 (after): sorted part (size 3)Pass 2 (after): sorted part (size 3)Pass 2 (after): unsorted partPass 2 (after): unsorted part235711No ChangeComparison in Pass 3Pass 3 (before): sorted part (size 3)Pass 3 (before): sorted part (size 3)Pass 3 (before): sorted part (size 3)Pass 3 (before): unsorted partPass 3 (before): unsorted part235711Pass 3 (after): sorted part (size 4)Pass 3 (after): sorted part (size 4)Pass 3 (after): sorted part (size 4)Pass 3 (after): sorted part (size 4)Pass 3 (after): unsorted part235711No ChangeComparison in Pass 4Pass 4 (before): sorted part (size 4)Pass 4 (before): sorted part (size 4)Pass 4 (before): sorted part (size 4)Pass 4 (before): sorted part (size 4)Pass 4 (before): unsorted part235711Pass 4 (after): sorted part (size 5)Pass 4 (after): sorted part (size 5)Pass 4 (after): sorted part (size 5)Pass 4 (after): sorted part (size 5)Pass 4 (after): sorted part (size 5)235711No ChangeInsertion Sort for List 2List 2:Original list element (index 1)Original list element (index 2)Original list element (index 3)Original list element (index 4)Original list element (index 5)117532Comparison in Pass 1Pass 1 (before): sorted part (size 1)Pass 1 (before): unsorted partPass 1 (before): unsorted partPass 1 (before): unsorted partPass 1 (before): unsorted part117532Pass 1 (after): sorted part (size 2)Pass 1 (after): sorted part (size 2)Pass 1 (after): unsorted partPass 1 (after): unsorted partPass 1 (after): unsorted part117532SwapPass 1 (after): sorted part (size 2)Pass 1 (after): sorted part (size 2)Pass 1 (after): unsorted partPass 1 (after): unsorted partPass 1 (after): unsorted part711532Comparison in Pass 2Pass 2 (before): sorted part (size 3)Pass 2 (before): sorted part (size 3)Pass 2 (before): sorted part (size 3)Pass 2 (before): unsorted partPass 2 (before): unsorted part711532SwapPass 2 (step 1): sorted part (size 3)Pass 2 (step 1): sorted part (size 3)Pass 2 (step 1): sorted part (size 3)Pass 2 (step 1): unsorted partPass 2 (step 1): unsorted part751132SwapPass 2 (after): sorted part (size 3)Pass 2 (after): sorted part (size 3)Pass 2 (after): sorted part (size 3)Pass 2 (after): unsorted partPass 2 (after): unsorted part571132Comparison in Pass 3Pass 3 (before): sorted part (size 4)Pass 3 (before): sorted part (size 4)Pass 3 (before): sorted part (size 4)Pass 3 (before): sorted part (size 4)Pass 3 (before): unsorted part571132SwapPass 3 (step 1): sorted part (size 4)Pass 3 (step 1): sorted part (size 4)Pass 3 (step 1): sorted part (size 4)Pass 3 (step 1): sorted part (size 4)Pass 3 (step 1): unsorted part573112SwapPass 3 (step 2): sorted part (size 4)Pass 3 (step 2): sorted part (size 4)Pass 3 (step 2): sorted part (size 4)Pass 3 (step 2): sorted part (size 4)Pass 3 (step 2): unsorted part537112SwapPass 3 (after): sorted part (size 4)Pass 3 (after): sorted part (size 4)Pass 3 (after): sorted part (size 4)Pass 3 (after): sorted part (size 4)Pass 3 (after): unsorted part357112Comparison in Pass 4Pass 4 (before): sorted part (size 5)Pass 4 (before): sorted part (size 5)Pass 4 (before): sorted part (size 5)Pass 4 (before): sorted part (size 5)Pass 4 (before): sorted part (size 5)357112SwapPass 4 (step 1): sorted part (size 5)Pass 4 (step 1): sorted part (size 5)Pass 4 (step 1): sorted part (size 5)Pass 4 (step 1): sorted part (size 5)Pass 4 (step 1): sorted part (size 5)357211SwapPass 4 (step 2): sorted part (size 5)Pass 4 (step 2): sorted part (size 5)Pass 4 (step 2): sorted part (size 5)Pass 4 (step 2): sorted part (size 5)Pass 4 (step 2): sorted part (size 5)352711SwapPass 4 (step 3): sorted part (size 5)Pass 4 (step 3): sorted part (size 5)Pass 4 (step 3): sorted part (size 5)Pass 4 (step 3): sorted part (size 5)Pass 4 (step 3): sorted part (size 5)325711SwapPass 4 (after): sorted part (size 5)Pass 4 (after): sorted part (size 5)Pass 4 (after): sorted part (size 5)Pass 4 (after): sorted part (size 5)Pass 4 (after): sorted part (size 5)235711
Diagrammatic representation of Insertion Sort for List 1 and List 2
Insertion sort keeps two parts: sorted list and unsorted list. Each element from the unsorted list is inserted into the correct position in the sorted list.
List 1 will make the minimum number of comparisons because it is already in ascending order.
Diagrammatic representation (Sorted | Unsorted)
List 1: 2 3 5 7 11 (already sorted)
Pass 1: [2] | [3 5 7 11] → compare 3 with 2 → no shift
Pass 2: [2 3] | [5 7 11] → compare 5 with 3 → no shift
Pass 3: [2 3 5] | [7 11] → compare 7 with 5 → no shift
Pass 4: [2 3 5 7] | [11] → compare 11 with 7 → no shift
✅ Comparisons are minimum (only 1 comparison each pass).
List 2: 11 7 5 3 2 (reverse order)
Pass 1: [11] | [7 5 3 2] → 7 compares with 11 → shift (1 comparison)
Pass 2: [7 11] | [5 3 2] → 5 compares with 11, then 7 → shift (2 comparisons)
Pass 3: [5 7 11] | [3 2] → 3 compares with 11, 7, 5 → shift (3 comparisons)
Pass 4: [3 5 7 11] | [2] → 2 compares with 11, 7, 5, 3 → shift (4 comparisons)
✅ This needs the maximum comparisons.
Final conclusion: ✅ We can see that List 1 requires 4 comparisons in total whereas List 2 requires 11 comparisons in total. So, we can conclude that List 1 makes the minimum number of comparisons.
Question 4
4. 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 to get median.)
Answer 4
Python Program to find the median of a given list:
def bubble_sort(num_list):
    """
    Sorts the list in ascending order using Bubble Sort.
    (Adjacent elements are compared and swapped if unordered.)
    """
    n = len(num_list)

    # Number of passes = n-1 (in general)
    for i in range(n):
        for j in range(0, n - i - 1):
            # If current element is bigger than next element, swap them
            if num_list[j] > num_list[j + 1]:
                num_list[j], num_list[j + 1] = num_list[j + 1], num_list[j]


def find_median(num_list):
    """
    Finds median of a list:
    - If odd number of terms: center term
    - If even number of terms: average of two middle terms
    """
    bubble_sort(num_list)  # sorting first using Bubble Sort

    n = len(num_list)
    mid = n // 2

    if n % 2 == 1:
        # Odd count -> middle element
        return num_list[mid]
    else:
        # Even count -> average of two middle elements
        return (num_list[mid - 1] + num_list[mid]) / 2


# ---- Input and output ----
raw = input("Enter numbers separated by space: ")
num_list = [int(x) for x in raw.split()]
median_value = find_median(num_list)

print("Sorted List:", num_list)
print("Median:", median_value)
Sample Output 1:
Enter numbers separated by space: 12 4 7 9 3
Sorted List: [3, 4, 7, 9, 12]
Median: 7
Sample Output 2:
Enter numbers separated by space: 10 2 8 4
Sorted List: [2, 4, 8, 10]
Median: 6.0
Question 5
5. All the branches of XYZ school conducted an aptitude test for all the students in the age group 14 – 16. There were a total of n students. The marks of n students are stored in a list. Write a program using a user defined function that accepts a list of marks as an argument and calculates the ‘xth’ percentile (where x is any number between 0 and 100). You are required to perform the following steps to be able to calculate the ‘xth’ percentile.
Note: Percentile is a measure of relative performance i.e. it is calculated based on a candidate’s performance with respect to others. For example: If a candidate’s score is in the 90th percentile, that means she/he scored better than 90% of people who took the test.
Steps to calculate the xth percentile:
I.
Order all the values in the data set from smallest to largest using Selection Sort. In general any of the sorting methods can be used.
II.
Calculate index by multiplying x percent by the total number of values, n.
For Example: to find 90th percentile for 120 students:
0.90 * 120 = 108
III.
Ensure that the index is a whole number by using math.round().
IV.
Display the value at the index obtained in Step 3.
The corresponding value in the list is the xth percentile.
Answer 5
Steps:
I.
Order all values in ascending order using Selection Sort.
II.
Calculate position = (x / 100) × n.
III.
Round the position to a whole number using round().
IV.
Display the value at that position (convert to 0-based index).
Program:
def selection_sort(marks):
    """
    Sorts the list in ascending order using Selection Sort.
    (Smallest element from unsorted part is selected and swapped.)
    """
    n = len(marks)

    for i in range(n):
        min_index = i
        for j in range(i + 1, n):
            if marks[j] < marks[min_index]:
                min_index = j
        if min_index != i:
            marks[i], marks[min_index] = marks[min_index], marks[i]


def xth_percentile(marks, x):
    """
    Calculates xth percentile using the given steps.
    """
    selection_sort(marks)  # Step I

    n = len(marks)
    position = (x / 100) * n  # Step II
    position = round(position)  # Step III

    # Convert to 0-based index and keep within range
    index = position - 1
    if index < 0:
        index = 0
    if index >= n:
        index = n - 1

    return marks[index], marks


# ---- Input and output ----
raw = input("Enter marks separated by space: ")
marks_list = [int(x) for x in raw.split()]
x = int(input("Enter percentile (0-100): "))

value, sorted_marks = xth_percentile(marks_list, x)

print("Sorted Marks:", sorted_marks)
print("Percentile Value:", value)
Sample Output 1:
Enter marks separated by space: 55 72 91 60 39 85 77 68 87 49
Enter percentile (0-100): 90
Sorted Marks: [39, 49, 55, 60, 68, 72, 77, 85, 87, 91]
Percentile Value: 87
Sample Output 2:
Enter marks separated by space: 10 20 30 40 50
Enter percentile (0-100): 50
Sorted Marks: [10, 20, 30, 40, 50]
Percentile Value: 30
Question 6
6. During admission in a course, the names of the students are inserted in ascending order. Thus, performing the sorting operation at the time of inserting elements in a list. Identify the type of sorting technique being used and write a program using a user defined function that is invoked every time a name is input and stores the name in ascending order of names in the list.
Answer 6
Technique:
✅ The technique is Insertion Sort, because each new name is inserted at its appropriate position in the already sorted list.
Program:
def insert_name_in_sorted_list(name_list, new_name):
    """
    Inserts new_name into name_list so that the list remains
    in ascending order (a-z). This is like Insertion Sort idea.
    """
    pos = 0

    # Find correct position for insertion
    while pos < len(name_list) and name_list[pos].lower() <= new_name.lower():
        pos += 1

    # Insert at the found position
    name_list.insert(pos, new_name)


# ---- Sample run ----
names = []

n = int(input("How many names? "))

for i in range(n):
    name = input("Enter name: ")
    insert_name_in_sorted_list(names, name)  # invoked every time
    print("List after insertion:", names)

print("Final sorted list:", names)
Sample Output:
How many names? 4
Enter name: Riya
List after insertion: ['Riya']
Enter name: Aman
List after insertion: ['Aman', 'Riya']
Enter name: Zoya
List after insertion: ['Aman', 'Riya', 'Zoya']
Enter name: Bharat
List after insertion: ['Aman', 'Bharat', 'Riya', 'Zoya']
Final sorted list: ['Aman', 'Bharat', 'Riya', 'Zoya']