MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Elementary Sorting Algorithms: Bubble, Selection & Insertion Sort (O(n²))0%
Study Materials
Data Structures & AlgorithmsProgress 0%
1.1Introduction to DSA, Big-O, Big-Omega & Big-Theta Notations1.2Time Complexity Calculation Rules & Common Runtime Patterns1.3Space Complexity, Auxiliary Memory & Stack vs Heap Allocation
6.1Binary Search: Search Space Elimination, Lower Bound & Upper Bound6.2Binary Search on Answer Space: Allocation & Feasibility Checks6.3Elementary Sorting Algorithms: Bubble, Selection & Insertion Sort (O(n²))6.4Merge Sort: Divide-and-Conquer Paradigm & Stability Analysis6.5Quick Sort: Lomuto vs Hoare Partitioning & Pivot Strategies
HomeTutorialsData Structures & AlgorithmsElementary Sorting Algorithms: Bubble, Selection & Insertion Sort (O(n²))
Merge Sort: Divide-and-Conquer Paradigm & Stability Analysis

Elementary Sorting Algorithms: Bubble, Selection & Insertion Sort (O(n²))

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

Sorting rearranges elements in a sequence into monotonic ascending or descending order. While advanced algorithms (Merge Sort, Quick Sort) dominate big data, understanding the elementary trio—Bubble Sort, Selection Sort, and Insertion Sort—is critical for mastering algorithmic trade-offs, stability, and small-data optimizations.


1. Real-World Analogies

  • Bubble Sort (Fizzy Soda): Heavy elements sink to the bottom while lighter elements bubble up to the surface one-by-one through adjacent pairwise swaps.
  • Selection Sort (Picking the MVP): You scan the entire crowd, select the absolute shortest person, and place them at index 0. Then scan the remainder, find the next shortest, and place them at index 1.
  • Insertion Sort (Arranging Playing Cards): You hold cards in your hand. As you pick up each new card from the deck, you slide it into its correct sorted position among the cards already in your hand.

2. The Big-O Comparison Table

AlgorithmBest TimeAverage TimeWorst TimeSpaceStable?Adaptive?
Bubble Sort$O(n)$ (with flag)$O(n^2)$$O(n^2)$$O(1)$YesYes
Selection Sort$O(n^2)$$O(n^2)$$O(n^2)$$O(1)$NoNo
Insertion Sort$O(n)$$O(n^2)$$O(n^2)$$O(1)$YesYes

Note: An algorithm is Stable if equal elements preserve their original relative order after sorting.


3. Algorithm 1: Optimized Bubble Sort ($O(n)$ Best Case)

1def bubble_sort(arr: list[int]) -> list[int]:
2 n = len(arr)
3 for i in range(n):
4 swapped = False
5 # Last i elements are already in sorted place!
6 for j in range(0, n - i - 1):
7 if arr[j] > arr[j + 1]:
8 arr[j], arr[j + 1] = arr[j + 1], arr[j]
9 swapped = True
10 # If no swaps occurred, array is already sorted!
11 if not swapped:
12 break
13 return arr

4. Algorithm 2: Selection Sort (Minimizing Memory Writes)

Selection Sort performs at most $n$ total swaps, making it useful when writing to flash memory where write operations are costly:

1def selection_sort(arr: list[int]) -> list[int]:
2 n = len(arr)
3 for i in range(n):
4 min_idx = i
5 for j in range(i + 1, n):
6 if arr[j] < arr[min_idx]:
7 min_idx = j
8 # Swap found minimum with first unsorted element
9 arr[i], arr[min_idx] = arr[min_idx], arr[i]
10 return arr

5. Algorithm 3: Insertion Sort (King of Nearly-Sorted Data)

Insertion Sort is blazing fast for small arrays ($n \le 30$) or nearly-sorted data. Production algorithms like Timsort (used in Python sorted() and Java Arrays.sort()) use Insertion Sort as their base-case engine!

Modern JavaScript / TypeScript Implementation:

1export function insertionSort(arr: number[]): number[] {
2 for (let i = 1; i < arr.length; i++) {
3 const key = arr[i];
4 let j = i - 1;
5 
6 // Shift elements of arr[0...i-1] that are greater than key to the right
7 while (j >= 0 && arr[j] > key) {
8 arr[j + 1] = arr[j];
9 j--;
10 }
11 arr[j + 1] = key;
12 }
13 return arr;
14}

6. Trace Table: Insertion Sort on [5, 2, 4, 6, 1]

Pass ($i$)KeySubarray before insertionComparisons & ShiftsSubarray after pass
12[5]5 > 2 → shift 5 right[2, 5, 4, 6, 1]
24[2, 5]5 > 4 → shift 5 right[2, 4, 5, 6, 1]
36[2, 4, 5]5 < 6 → 0 shifts[2, 4, 5, 6, 1]
41[2, 4, 5, 6]Shift 6, 5, 4, 2 right[1, 2, 4, 5, 6]

Interactive Quiz• Knowledge Check

Multiple Choice Questions

Question 1
Why does Insertion Sort run in $O(n)$ linear time on an already-sorted array?
Question 2
What does it mean for a sorting algorithm to be "Stable"?
Question 3
Which sorting algorithm performs the minimum number of write operations (at most $n$ swaps in total)?
Question 4
Why is Selection Sort considered an "Unstable" sorting algorithm?
Question 5
Why do modern production hybrid sorting engines like Timsort switch to Insertion Sort for small subarrays ($n \le 32$)?

Next Lesson

Merge Sort: Divide-and-Conquer Paradigm & Stability Analysis

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Binary Search on Answer Space: Allocation & Feasibility ChecksMerge Sort: Divide-and-Conquer Paradigm & Stability Analysis

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Data Structures & Algorithms with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext