Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🧱 Unit 1 – Data Structures & Algorithms  ·  Lesson 12

Sorting: Bubble, Selection, Insertion

What is sorting?

Sorting means arranging data in ascending or descending order – marks from highest to lowest, names alphabetically. Sorted data is much faster to search (binary search needs it).

Unsorted list used in every example →807113213-9445

Bubble sort

Compare adjacent elements and swap them if they are in the wrong order. After each pass the largest remaining element “bubbles” to its final place at the end.

After pass 1 →781-9413
13 has reached its final place
Python
def bubble_sort(a):
    n = len(a)
    for i in range(n - 1):              # passes
        swapped = False
        for j in range(n - 1 - i):      # last i items already in place
            if a[j] > a[j + 1]:
                a[j], a[j + 1] = a[j + 1], a[j]
                swapped = True
        print('Pass', i + 1, ':', a)
        if not swapped:                 # already sorted -> stop early
            break
nums = [8, 7, 13, 1, -9, 4]
bubble_sort(nums)
Pass 1 : [7, 8, 1, -9, 4, 13] Pass 2 : [7, 1, -9, 4, 8, 13] Pass 3 : [1, -9, 4, 7, 8, 13] Pass 4 : [-9, 1, 4, 7, 8, 13] Pass 5 : [-9, 1, 4, 7, 8, 13]

Selection sort

Divide the list into a sorted left part and an unsorted right part. In each pass, select the smallest element of the unsorted part and swap it to the front of that part.

After pass 1 →-9713184
-9 was the smallest; swapped with 8
Python
def selection_sort(a):
    n = len(a)
    for i in range(n - 1):
        m = i                           # index of smallest so far
        for j in range(i + 1, n):
            if a[j] < a[m]:
                m = j
        a[i], a[m] = a[m], a[i]         # put smallest at position i
        print('Pass', i + 1, ':', a)
nums = [8, 7, 13, 1, -9, 4]
selection_sort(nums)
Pass 1 : [-9, 7, 13, 1, 8, 4] Pass 2 : [-9, 1, 13, 7, 8, 4] Pass 3 : [-9, 1, 4, 7, 8, 13] Pass 4 : [-9, 1, 4, 7, 8, 13] Pass 5 : [-9, 1, 4, 7, 8, 13]

Insertion sort

Like arranging playing cards in your hand: take the next element and insert it at the correct position in the already-sorted left part, shifting bigger items to the right.

After pass 3 →17813-94
Highlighted part is sorted
Python
def insertion_sort(a):
    for i in range(1, len(a)):
        key = a[i]                      # card to insert
        j = i - 1
        while j >= 0 and a[j] > key:    # shift bigger items right
            a[j + 1] = a[j]
            j -= 1
        a[j + 1] = key
        print('Pass', i, ':', a)
nums = [8, 7, 13, 1, -9, 4]
insertion_sort(nums)
Pass 1 : [7, 8, 13, 1, -9, 4] Pass 2 : [7, 8, 13, 1, -9, 4] Pass 3 : [1, 7, 8, 13, -9, 4] Pass 4 : [-9, 1, 7, 8, 13, 4] Pass 5 : [-9, 1, 4, 7, 8, 13]

Sorting strings / descending

Python
def bubble_desc(names):
    n = len(names)
    for i in range(n - 1):
        for j in range(n - 1 - i):
            if names[j] < names[j + 1]:     # > becomes < for descending
                names[j], names[j + 1] = names[j + 1], names[j]
    return names
print(bubble_desc(['Ravi', 'Asha', 'Neha', 'Kabir']))
['Ravi', 'Neha', 'Kabir', 'Asha']

Time complexity

For n items, simple sorts compare about n×(n-1)/2 pairs, which grows like n². Doubling the data makes them about four times slower.

Python
def count_bubble(a):
    a = a[:]; comps = swaps = 0
    for i in range(len(a) - 1):
        for j in range(len(a) - 1 - i):
            comps += 1
            if a[j] > a[j + 1]:
                a[j], a[j + 1] = a[j + 1], a[j]; swaps += 1
    return comps, swaps
for data in [[1, 2, 3, 4, 5], [5, 4, 3, 2, 1], [3, 1, 4, 5, 2]]:
    print(data, '-> comparisons, swaps =', count_bubble(data))
[1, 2, 3, 4, 5] -> comparisons, swaps = (10, 0) [5, 4, 3, 2, 1] -> comparisons, swaps = (10, 10) [3, 1, 4, 5, 2] -> comparisons, swaps = (10, 4)
Comparisons grow quickly01000200030004000ncomparisons10204080
n(n-1)/2 for bubble/selection sort

Comparison

SortBestAverage / WorstIdea
BubbleO(n)O(n²)Swap neighbours; largest bubbles to the end
SelectionO(n²)O(n²)Pick the smallest, put it in front
InsertionO(n)O(n²)Insert each item into the sorted left part

Frequently Asked Questions

How many passes does bubble sort need for n elements?
At most n-1 passes. With the swapped flag it stops early when a pass makes no swaps.
Which sort makes the fewest swaps?
Selection sort makes at most one swap per pass, so at most n-1 swaps in total.
Which sort is best for an almost-sorted list?
Insertion sort, because each new item moves only a short distance; its best case is O(n).
← Class 12 Computer Science
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicSearching: Linear, Binary, Hashing Your progress: 12 / 26 (46%) · Lesson 13 / 26 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free