Introduction
Sorting is one of the most fundamental operations in computer science.
It involves arranging data in a specific order (ascending or descending).
Efficient sorting helps improve the performance of searching and data processing tasks.
In this blog, we will explore three basic sorting algorithms:
- Bubble Sort
- Selection Sort
- Insertion Sort
1. Bubble Sort
Concept
Bubble Sort repeatedly compares adjacent elements and swaps them if they are in the wrong order.
Larger elements “bubble up” to the end of the list.
Algorithm
- Compare adjacent elements
- Swap if needed
- Repeat for all elements
- Continue until array is sorted
Code (Python)
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
Complexity
- Time: O(n²)
- Space: O(1)
Key Point
- Simple to understand
- Not efficient for large data
2. Selection Sort
Concept
Selection Sort selects the smallest element from the unsorted part and places it at the correct position.
Algorithm
- Find minimum element
- Swap it with first element
- Repeat for remaining array
Code (Python)
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_index = i
for j in range(i + 1, n):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
return arr
Complexity
- Time: O(n²)
- Space: O(1)
Key Point
- Fewer swaps compared to Bubble Sort
- Still inefficient for large inputs
3. Insertion Sort
Concept
Insertion Sort builds the sorted array one element at a time by inserting elements into their correct position.
Algorithm
- Take one element
- Compare with previous elements
- Insert it in correct position
- Repeat for all elements
Code (Python)
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
Complexity
- Time: O(n²)
- Space: O(1)
Key Point
- Efficient for small or nearly sorted data
- Used in real-world hybrid algorithms
Conclusion
Sorting algorithms are essential building blocks in programming.
- Bubble Sort is easiest to understand
- Selection Sort reduces swaps
- Insertion Sort is efficient for small datasets.
Top comments (0)