2nd PUC Computer Science Chapter 5 Sorting Notes | Bubble Sort, Selection Sort, Insertion Sort
Complete Short Notes & Exam Preparation Guide
Bubble Sort • Selection Sort • Insertion Sort • Time Complexity of Algorithms
Based on the NCERT textbook PDF only.
verakworld.com📚 Table of Contents
- 5.1 Introduction
- 5.2 Bubble Sort
- 5.3 Selection Sort
- 5.4 Insertion Sort
- 5.5 Time Complexity of Algorithms
- Summary
- Exercise / Important Questions
- Quick Revision
- Final Revision Checklist
📖 Chapter Overview
Sorting is the process of ordering or arranging a given collection of elements in some particular order. Numbers can be arranged in ascending or descending order. Strings can be arranged alphabetically or according to their length.
Examples given in the textbook include words in a dictionary being arranged alphabetically, examination seats being ordered according to candidates’ roll numbers, and a list of students being sorted based on height or weight.
A sorted collection makes searching easier. The textbook uses the example of a dictionary: finding a word in an unordered dictionary would require searching page by page, whereas alphabetical ordering makes the search process easier.
Sorting a large number of items can require substantial time. This extra time, called overhead, can nevertheless be worthwhile compared with the time required to find an element in an unsorted list.
This chapter discusses three sorting methods and their implementation using Python: Bubble Sort, Selection Sort and Insertion Sort.
verakworld.com5.1 Introduction
Ways of Sorting Mentioned in the Chapter
- Numbers can be sorted in ascending (increasing) order.
- Numbers can be sorted in descending (decreasing) order.
- Strings can be sorted alphabetically from a-z or z-a.
- Strings can also be sorted according to their length.
- Words in a dictionary are sorted alphabetically.
- Examination seats can be ordered according to candidates’ roll numbers.
- A list of students can be sorted based on height or weight.
5.2 Bubble Sort
Meaning of Swapping
Swapping two elements means changing their positions with each other.
Pass
In the algorithm, every iteration through each element of a list is called a pass.
Number of Passes
For a list containing n elements, bubble sort makes a total of n − 1 passes to sort the list.
Working of Bubble Sort
- Adjacent elements are compared.
- For ascending order, if the first element is bigger than the second, they are swapped.
- If they are already in the correct order, no change is made.
- The comparisons continue until the end of the list is reached.
- After each pass, the largest element reaches its correct position at the end.
- The largest element is said to be “bubbled up”.
- The sorted element is not considered in the remaining passes.
- Therefore, the list of elements considered becomes smaller in successive passes.
numList:
Comparison in Pass 1
Comparison in Pass 2
Comparison in Pass 3
Comparison in Pass 4
Important Observation from Figure 5.1
The list becomes sorted in the 4th pass itself. However, the normal bubble sort technique performs a redundant 5th pass, which does not result in any swap.
Algorithm 5.1: Bubble Sort
BUBBLESORT( numList, n) Step 1: SET i = 0 Step 2: WHILE i< n REPEAT STEPS 3 to 8 Step 3: SET j = 0 Step 4: WHILE j< n-i-1,REPEAT STEPS 5 to 7 Step 5: IF numList[j] > numList[j+1] THEN Step 6: swap(numList[j],numList[j+1]) Step 7: SET j=j+1 Step 8: SET i=i+1verakworld.com
💻 Program 5-1 — Implementation of Bubble Sort using Python
def bubble_Sort(list1):
n = len(list1)
for i in range(n): # Number of passes
for j in range(0, n-i-1):
# size -i-1 because last i elements are already sorted
#in previous passes
if list1[j] > list1[j+1] :
# Swap element at jth position with (j+1)th position
list1[j], list1[j+1] = list1[j+1], list1[j]
numList = [8, 7, 13, 1, -9, 4]
bubble_Sort(numList)
The sorted list is : -9 1 4 7 8 13
Activity 5.1
Algorithm 5.1 sorts a list in ascending order. Write a bubble sort algorithm to sort a list in descending order.
verakworld.comActivity 5.2
Apply bubble sort technique to sort a list of elements: numList2 = [8, 7, 6, 5, 4]. Show the positions of elements in the list after each pass. In which pass does the last swap happen?
verakworld.com5.3 Selection Sort
Basic Structure
| Part | Description |
|---|---|
| Left list | Contains the sorted elements. |
| Right list | Contains the unsorted elements. |
| Initially | The left list is empty and the right list contains all elements. |
Number of Passes
For a list containing n elements, selection sort makes n − 1 passes.
Working in Ascending Order
- In the first pass, traverse all elements in the unsorted list.
- Find the smallest element.
- Swap it with the leftmost element of the unsorted list.
- The selected element becomes the first element of the sorted list.
- It is not considered in further passes.
- In the second pass, find the next smallest element from the remaining unsorted elements.
- Swap it with the leftmost element of the unsorted list.
- Continue until n − 1 smallest elements are found and placed.
- The nth element is the last element and is already in its place.
numList:
Comparison in Pass 1
Comparison in Pass 2
Comparison in Pass 3
Comparison in Pass 4
Comparison in Pass 5
Algorithm 5.2: Selection Sort
SELECTIONSORT( numList, n) Step 1: SET i=0 Step 2: WHILE i< n REPEAT STEPS 3 to 11 Step 3: SET min = i, flag = 0 Step 4: SET j= i+1 Step 5: WHILE j<n, REPEAT STEPS 6 to 10 Step 6: IF numList[j] < numList[min] THEN Step 7: min = j Step 8: flag = 1 Step 9: IF flag = 1 THEN Step 10: swap(numList[i],numList[min]) Step 11: SET i=i+1
💻 Program 5-2 — Implementation of Selection Sort using Python
def selection_Sort(list2):
flag = 0 #to decide when to swap
n=len(list2)
for i in range(n): # Traverse through all list elements
min = i
for j in range(i + 1, len(list2)): #the left elements
#are already sorted in previous passes
if list2[j] < list2[min]: # element at j is smaller
#than the current min element
min = j
flag = 1
if flag == 1 : # next smallest element is found
list2[min], list2[i] = list2[i], list2[min]
numList = [8, 7, 13, 1, -9, 4]
selection_Sort(numList)
print ("The sorted list is :")
for i in range(len(numList)):
print (numList[i], end=" ")
The sorted list is : -9 1 4 7 8 13
Activity 5.3
Consider a list of 10 elements:
randList = [7,11,3,10,17,23,1,4,21,5]
Determine the partially sorted list after four complete passes of selection sort.
verakworld.com5.4 Insertion Sort
Working of Insertion Sort
- The list is divided into a sorted part and an unsorted part.
- Elements from the unsorted list are considered one by one.
- Each element is inserted into its appropriate position in the sorted list.
- In each pass, the sorted list is traversed from the backward direction to find the insertion position.
- If the element to be inserted is smaller than an element in the sorted list, that element is shifted towards the right.
- The shifting creates space for the new element.
- The process continues until all elements in the unsorted list have been inserted.
- The final result is a sorted list arranged in ascending order.
Pass 1
The unsorted list has n − 1 elements and the sorted list has a single element. The first unsorted element is compared with the sorted element. If it is smaller, the sorted element is shifted to the right and the new element is inserted.
Subsequent Passes
The first element of the unsorted list is compared with the elements of the sorted list starting from the backward direction until the appropriate position for insertion is found. The sorted elements are shifted towards the right to create space for the element.
numList:
Comparison in Pass 1
Comparison in Pass 2
Comparison in Pass 3
Comparison in Pass 4
Comparison in Pass 5
Algorithm 5.3: Insertion Sort
INSERTIONSORT( numList, n) Step 1: SET i=1 Step 2: WHILE i< n REPEAT STEPS 3 to 9 Step 3: temp = numList[i] Step 4: SET j = i-1 Step 5: WHILE j> = 0 and numList[j]>temp,REPEAT STEPS 6 to 7 Step 6: numList[j+1] = numList[j] Step 7: SET j=j-1 Step 8: numList[j+1] = temp #insert temp at position j Step 9: set i=i+1verakworld.com
💻 Program 5-3 — Implementation of Insertion Sort using Python
def insertion_Sort(list3):
n= len(list3)
for i in range(n): # Traverse through all elements
temp = list3[i]
j = i-1
while j >=0 and temp< list3[j] :
list3[j+1] = list3[j]
j = j-1
list3[j+1] = temp
numList = [8, 7, 13, 1, -9, 4]
insertion_Sort(numList)
print (“The sorted list is :”)
for i in range(len(numList)):
print (numList[i], end=" ")
The sorted list is : -9 1 4 7 8 13
Activity 5.4
Consider a list of 10 elements:
Array = [7,11,3,10,17,23,1,4,21,5]
Determine the partially sorted list after three complete passes of insertion sort.
verakworld.com5.5 Time Complexity of Algorithms
There can be more than one approach to solve a problem using a computer. Different algorithms for the same problem may require different amounts of processing time.
For a small set of data elements, the difference in time and memory required by different algorithms may not be significant. However, sorting algorithms may have to work with huge amounts of data in real-world situations. In such cases, total time utilisation becomes significant.
Therefore, it is important to consider the time complexity of an algorithm before using it for a real-world data set.
Computer scientists study time complexity to understand how a sorting algorithm behaves when the order of input elements changes or when the number of elements increases or decreases.
Basic Rules for Estimating Time Complexity
| Structure of Algorithm | Time Complexity | Type |
|---|---|---|
| No loop | 1 | Constant time algorithm |
| A loop, usually 1 to n | n | Linear time algorithm |
| A loop within a loop (nested loop) | n² | Quadratic time algorithm |
| A nested loop and also a single loop | Estimated based on the nested loop | Based on the nested-loop complexity |
Time Complexity of the Three Sorting Algorithms
The Python programs of Bubble Sort, Selection Sort and Insertion Sort each contain a nested loop. According to the rules given in the textbook, all three sorting algorithms have a time complexity of n².
| Sorting Algorithm | Time Complexity |
|---|---|
| Bubble Sort | n² |
| Selection Sort | n² |
| Insertion Sort | n² |
📌 Summary
- Sorting is the process of placing or rearranging a collection of elements into a particular order.
- Bubble Sort is the simplest sorting algorithm that repeatedly swaps adjacent elements when they are unordered in n−1 passes.
- In Selection Sort, the smallest element is selected from the unsorted array and swapped with the leftmost element.
- Insertion Sort places an element of a list at its suitable place in each pass. It is similar to placing cards at their right position while playing cards.
- Complexity analysis is performed to explain how an algorithm will perform when the input grows larger.
❓ Questions & Answers
1-Mark Questions
2-Mark Questions
3-Mark Questions
4/5-Mark Questions
📊 Important Differences
| Basis | Bubble Sort | Selection Sort | Insertion Sort |
|---|---|---|---|
| Basic idea | Repeatedly compares adjacent elements and swaps unordered elements. | Selects the smallest element from the unsorted list and swaps it into position. | Inserts an unsorted element into its appropriate position in the sorted list. |
| Parts of list | Sorted elements at the end are excluded from later passes. | Left part is sorted and right part is unsorted. | List is divided into sorted and unsorted parts. |
| Important operation | Adjacent comparison and swapping. | Finding the smallest element and swapping. | Shifting and inserting. |
| Time complexity in this chapter | n² | n² | n² |
📝 Important Questions
1 Mark
- Define sorting.
- What is swapping?
- What is a pass?
- How many passes does Bubble Sort make for n elements?
- What is time complexity?
- What is a constant time algorithm?
- What is a linear time algorithm?
- What is a quadratic time algorithm?
2 Marks
- Explain why sorting is useful.
- Explain Bubble Sort.
- Explain the sorted and unsorted lists in Selection Sort.
- Explain the basic idea of Insertion Sort.
- Explain the basic rules for estimating time complexity.
3 Marks
- Explain the working of Bubble Sort.
- Explain the working of Selection Sort.
- Explain the working of Insertion Sort.
- Explain the importance of time complexity.
4/5 Marks
- Write Algorithm 5.1 for Bubble Sort.
- Write the Python program for Bubble Sort.
- Write Algorithm 5.2 for Selection Sort.
- Write the Python program for Selection Sort.
- Write Algorithm 5.3 for Insertion Sort.
- Write the Python program for Insertion Sort.
- Explain the time complexity rules discussed in the chapter.
📘 Textbook Exercise
List 1: 63 42 21 9
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.
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.
Note: Percentile is a measure of relative performance. 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
- 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.
- Calculate index by multiplying x percent by the total number of values, n.
- Ensure that the index is a whole number by using math.round().
- Display the value at the index obtained in Step 3. The corresponding value in the list is the xth percentile.
Example given: To find 90th percentile for 120 students:
0.90*120 = 108
⚡ Quick Revision
Important Definitions
- Sorting: Ordering or arranging a collection of elements in a particular order.
- Swapping: Changing the positions of two elements.
- Pass: Every iteration through each element of a list.
- Time Complexity: Amount of time an algorithm takes to process given data.
Important Terms
- Ascending order
- Descending order
- Adjacent elements
- Sorted list
- Unsorted list
- Pass
- Swap
- Nested loop
- Constant time
- Linear time
- Quadratic time
Important Concepts
- Bubble Sort repeatedly compares adjacent elements.
- Selection Sort selects the smallest element.
- Insertion Sort inserts an element into its suitable position.
- All three sorting programs contain nested loops.
- The chapter gives n² as the time complexity of all three sorting algorithms.
Important Formulas / Values
- Bubble Sort passes for n elements = n − 1
- Selection Sort passes for n elements = n − 1
- Constant time = 1
- Linear time = n
- Quadratic time = n²
- Bubble Sort = n²
- Selection Sort = n²
- Insertion Sort = n²
Important Algorithms
- Algorithm 5.1 — Bubble Sort
- Algorithm 5.2 — Selection Sort
- Algorithm 5.3 — Insertion Sort
Important Programs
- Program 5-1 — Bubble Sort using Python
- Program 5-2 — Selection Sort using Python
- Program 5-3 — Insertion Sort using Python
Important Figures
- Figure 5.1 — Bubble Sort comparisons
- Figure 5.2 — Selection Sort comparisons
- Figure 5.3 — Insertion Sort comparisons
Exam Focus
- Definitions of sorting and time complexity
- Working of all three sorting techniques
- Algorithms 5.1, 5.2 and 5.3
- Python programs 5-1, 5-2 and 5-3
- Time complexity rules
- Textbook exercises and activities
💻 Important Syntax & Code Revision
Bubble Sort — Key Code Structure
for i in range(n):
for j in range(0, n-i-1):
if list1[j] > list1[j+1]:
list1[j], list1[j+1] = list1[j+1], list1[j]
verakworld.com
Selection Sort — Key Code Structure
for i in range(n):
min = i
for j in range(i + 1, len(list2)):
if list2[j] < list2[min]:
min = j
verakworld.com
Insertion Sort — Key Code Structure
temp = list3[i]
j = i-1
while j >=0 and temp< list3[j]:
list3[j+1] = list3[j]
j = j-1
list3[j+1] = temp
verakworld.com
🚀 Final Revision
Last-Minute Revision Checklist
- Sorting → arranging elements in a particular order.
- Bubble Sort → adjacent comparison + swapping.
- Bubble Sort → n−1 passes.
- Selection Sort → select smallest element from unsorted list.
- Selection Sort → n−1 passes.
- Insertion Sort → insert element into suitable position.
- Insertion Sort → sorted and unsorted parts.
- Time Complexity → time taken by an algorithm to process given data.
- No loop → 1 → Constant time.
- Single loop → n → Linear time.
- Nested loop → n² → Quadratic time.
- Bubble Sort → n².
- Selection Sort → n².
- Insertion Sort → n².
- Revise Algorithms 5.1, 5.2 and 5.3.
- Revise Programs 5-1, 5-2 and 5-3.
- Revise Figures 5.1, 5.2 and 5.3.
- Practise the textbook activities and exercises.