Array Sorting Algorithms in Python
Sorting algorithms are used to arrange elements in a list or array in a specific order, usually in
ascending or descending order. Below are some common sorting algorithms along with Python
implementations.
1. Bubble Sort
Bubble sort is a simple algorithm that repeatedly steps through the list, compares adjacent
elements, and swaps them if they are in the wrong order. The process repeats until the list is
sorted.
Time Complexity:
• Worst case: O(n²)
• Best case: O(n) (if already sorted)
• Average case: O(n²)
Python 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] # Swap
# Example usage
arr = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(arr)
print("Sorted array:", arr)
2. Selection Sort
Selection sort divides the list into two parts: the sorted part and the unsorted part. It repeatedly
selects the smallest element from the unsorted part and swaps it with the first unsorted
element.
Time Complexity:
• Worst case: O(n²)
• Best case: O(n²)
• Average case: O(n²)
Python Code:
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] # Swap
# Example usage
arr = [64, 34, 25, 12, 22, 11, 90]
selection_sort(arr)
print("Sorted array:", arr)
3. Insertion Sort
Insertion sort works by taking one element at a time and inserting it into its correct position in a
sorted portion of the list. It's similar to how you might sort playing cards in your hands.
Time Complexity:
• Worst case: O(n²)
• Best case: O(n) (if already sorted)
• Average case: O(n²)
Python Code:
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 usage
arr = [64, 34, 25, 12, 22, 11, 90]
insertion_sort(arr)
print("Sorted array:", arr)
4. Merge Sort
Merge sort is a divide-and-conquer algorithm. It divides the array into two halves, sorts each
half recursively, and then merges the sorted halves. Merge sort has better performance
compared to the previous algorithms.
Time Complexity:
• Worst case: O(n log n)
• Best case: O(n log n)
• Average case: O(n log n)
Python Code:
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
merge_sort(left_half)
merge_sort(right_half)
i=j=k=0
while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
arr[k] = left_half[i]
i += 1
else:
arr[k] = right_half[j]
j += 1
k += 1
while i < len(left_half):
arr[k] = left_half[i]
i += 1
k += 1
while j < len(right_half):
arr[k] = right_half[j]
j += 1
k += 1
# Example usage
arr = [64, 34, 25, 12, 22, 11, 90]
merge_sort(arr)
print("Sorted array:", arr)
5. Quick Sort
Quick sort is another divide-and-conquer algorithm. It selects a pivot element from the array,
partitions the other elements into two sub-arrays (elements less than the pivot and elements
greater than the pivot), and recursively sorts the sub-arrays.
Time Complexity:
• Worst case: O(n²) (if pivot is poorly chosen)
• Best case: O(n log n)
• Average case: O(n log n)
Python Code:
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
# Example usage
arr = [64, 34, 25, 12, 22, 11, 90]
sorted_arr = quick_sort(arr)
print("Sorted array:", sorted_arr)
6. Heap Sort
Heap sort is based on the binary heap data structure. It converts the array into a binary heap (a
complete binary tree) and repeatedly extracts the maximum element from the heap and places
it at the end of the array.
Time Complexity:
• Worst case: O(n log n)
• Best case: O(n log n)
• Average case: O(n log n)
Python Code:
import heapq
def heap_sort(arr):
heapq.heapify(arr) # Convert array into a min-heap
return [heapq.heappop(arr) for _ in range(len(arr))]
# Example usage
arr = [64, 34, 25, 12, 22, 11, 90]
sorted_arr = heap_sort(arr)
print("Sorted array:", sorted_arr)
7. Python’s Built-in Sort
Python provides a built-in method called sort() (for sorting in place) and sorted() (returns a new
sorted list). Both use Timsort (a hybrid sorting algorithm derived from merge sort and insertion
sort), which is highly efficient.
Time Complexity:
• Worst case: O(n log n)
• Best case: O(n) (for nearly sorted data)
• Average case: O(n log n)
Python Code:
arr = [64, 34, 25, 12, 22, 11, 90]
arr.sort() # Sorts the array in place
print("Sorted array:", arr)
# Or using sorted() to return a new sorted array
arr2 = [64, 34, 25, 12, 22, 11, 90]
sorted_arr2 = sorted(arr2)
print("Sorted array:", sorted_arr2)
Summary of Sorting Algorithms
Time Complexity Time Complexity Time Complexity Space
Algorithm
(Best) (Average) (Worst) Complexity
Bubble Sort O(n) O(n²) O(n²) O(1)
Selection
O(n²) O(n²) O(n²) O(1)
Sort
Insertion
O(n) O(n²) O(n²) O(1)
Sort
Merge Sort O(n log n) O(n log n) O(n log n) O(n)
Time Complexity Time Complexity Time Complexity Space
Algorithm
(Best) (Average) (Worst) Complexity
Quick Sort O(n log n) O(n log n) O(n²) O(log n)
Heap Sort O(n log n) O(n log n) O(n log n) O(1)
Python Sort O(n) O(n log n) O(n log n) O(n)
Each algorithm has its strengths and weaknesses, and the choice of which one to use depends
on the problem and the dataset. For practical purposes, Timsort (used in Python's sort()
method) is the most commonly used due to its performance and efficiency in handling both
sorted and unsorted data.