🔄 Different Sorting Methodologies in Python – Complete Guide
Hi All,
In this blog, I’ll explain the different sorting algorithms I learned, including their working, code, and complexity.
📌 What is Sorting?
Sorting is the process of arranging elements in a specific order:
- Ascending (small → large)
- Descending (large → small)
🧠1. Bubble Sort
💡 Idea:
Repeatedly compare adjacent elements and swap if needed.
💻 Code:
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)
🧠2. Selection Sort
💡 Idea:
Find the minimum element and place it at the beginning.
💻 Code:
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_idx = i
for j in range(i+1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
return arr
âš¡ Complexity:
- Time: O(n²)
- Space: O(1)
🧠3. Insertion Sort
💡 Idea:
Insert each element into its correct position in the sorted part.
💻 Code:
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)
🧠4. Merge Sort
💡 Idea:
Divide array into halves, sort, and merge.
💻 Code:
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left = arr[:mid]
right = arr[mid:]
merge_sort(left)
merge_sort(right)
i = j = k = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
k += 1
while i < len(left):
arr[k] = left[i]
i += 1
k += 1
while j < len(right):
arr[k] = right[j]
j += 1
k += 1
return arr
âš¡ Complexity:
- Time: O(n log n)
- Space: O(n)
🧠5. Quick Sort
💡 Idea:
Pick a pivot and partition the array.
💻 Code:
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[0]
left = [x for x in arr[1:] if x <= pivot]
right = [x for x in arr[1:] if x > pivot]
return quick_sort(left) + [pivot] + quick_sort(right)
âš¡ Complexity:
- Time: O(n log n) (average)
- Space: O(log n)
🧠6. Built-in Sort (Python)
💡 Idea:
Uses Timsort (combination of merge + insertion sort)
💻 Code:
arr = [5, 2, 9, 1]
arr.sort()
print(arr)
âš¡ Complexity:
- Time: O(n log n)
- Space: O(n)
📊 Comparison Table
| Algorithm | Time Complexity | Space | Stable |
|---|---|---|---|
| Bubble Sort | O(n²) | O(1) | Yes |
| Selection Sort | O(n²) | O(1) | No |
| Insertion Sort | O(n²) | O(1) | Yes |
| Merge Sort | O(n log n) | O(n) | Yes |
| Quick Sort | O(n log n) | O(log n) | No |
🧠Conclusion
From this, we can understand:
- Simple sorts → easy but slow
- Advanced sorts → fast but complex
- Built-in sort → best for real use
🚀 Final Thoughts
Learning sorting algorithms helps in:
- Improving problem-solving skills
- Understanding time complexity
- Cracking coding interviews
Top comments (0)