Learned Bubble, Selection, and Insertion Sort in Python

Day 18 of My 45-Day Python & DSA Journey Topic: Sorting Algorithms – Bubble Sort, Selection Sort & Insertion Sort Today, I stepped into another key part of DSA — sorting algorithms, which arrange data in a specific order (ascending or descending). Sorting improves the efficiency of many operations like searching and analysis. 🔹 What I Learned: 1. Bubble Sort Compares adjacent elements and swaps them if they’re in the wrong order. def bubble_sort(arr): n = len(arr) for i in range(n): for j in range(0, n-i-1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] return arr print(bubble_sort([5, 2, 9, 1])) Time Complexity: O(n²) Simple but not efficient for large datasets. 2. Selection Sort Selects the smallest element and places it in the correct position. def selection_sort(arr): for i in range(len(arr)): min_idx = i for j in range(i+1, len(arr)): if arr[j] < arr[min_idx]: min_idx = j arr[i], arr[min_idx] = arr[min_idx], arr[i] return arr Time Complexity: O(n²) Fewer swaps compared to Bubble Sort. 3. Insertion Sort Builds the sorted array one element at a time by inserting elements into their correct position. def insertion_sort(arr): for i in range(1, len(arr)): key = arr[i] j = i - 1 while j >= 0 and key < arr[j]: arr[j+1] = arr[j] j -= 1 arr[j+1] = key return arr Time Complexity: O(n²) Efficient for small or nearly sorted arrays. Reflection: Today’s practice showed me how sorting is the foundation of data organization. Each algorithm has a unique approach — simple logic, yet deep impact. Key Takeaway: “Sorting teaches patience — step-by-step logic leads to order from chaos.” Next: I’ll explore Advanced Sorting Algorithms — Merge Sort and Quick Sort, which are faster and widely used in real-world systems. #Python #DSA #SortingAlgorithms #BubbleSort #InsertionSort #SelectionSort #CodingJourney #LearningInPublic #CodeEveryday

To view or add a comment, sign in

Explore content categories