In Python, sorting a list is super easy using the built-in sort()
method or sorted()
function. But what if you’re asked to sort a list without using sort()
or sorted()
?
Whether you’re preparing for a coding interview or just want to understand sorting better, this guide will show you how to sort a list manually in Python.
Let’s break it down using simple logic and real code examples.
Table of Contents
Why Avoid Using sort()?
Sometimes, during technical interviews or coding challenges, you’re not allowed to use built-in methods like sort()
or sorted()
. This helps test your understanding of basic algorithms and problem-solving skills.
So, how can you sort a list without those?
You write your own sorting logic — and the most common ways to do that are with sorting algorithms like Bubble Sort, Selection Sort, or Insertion Sort.
Example: Bubble Sort in Python
Bubble Sort is one of the simplest sorting algorithms. It repeatedly steps through the list, compares adjacent items, and swaps them if they’re in the wrong order.
Here’s how to implement it:
def bubble_sort(arr):
n = len(arr)
for i in range(n):
# Last i elements are already in place
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
# Swap if the element found is greater
arr[j], arr[j + 1] = arr[j + 1], arr[j]
# Example usage
numbers = [5, 2, 9, 1, 7]
bubble_sort(numbers)
print(numbers)
Output:
[1, 2, 5, 7, 9]
Other Ways to Sort a List Without sort()
Using Selection Sort
Selection Sort works by selecting the smallest element and placing it at the beginning.
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]
# Example
numbers = [8, 3, 6, 2, 4]
selection_sort(numbers)
print(numbers)
Using Insertion Sort
Insertion Sort builds the final sorted list one item at a time.
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
# Example
numbers = [9, 1, 5, 3, 7]
insertion_sort(numbers)
print(numbers)
When Should You Do This?
You probably won’t need to sort this way in real-world projects. But it’s great for:
- Learning how sorting works under the hood
- Passing coding interviews
- Writing algorithms in coding competitions
Final Thoughts
Sorting a list without using Python’s sort()
is a great way to strengthen your understanding of algorithms. Bubble sort is the easiest to start with, while selection and insertion sort give you more practice with logic and loops.
Try writing your own version of each one and test with different lists. It’s one of the best ways to level up your Python skills