Sorting algorithms are a fundamental concept in computer science, and they play a crucial role in many applications. Here's a brief overview of some popular sorting algorithms.
Types of Sorting Algorithms
Comparison-based Algorithms:
- Bubble Sort: Simple but inefficient for large datasets.
- Selection Sort: Inefficient, but simple to implement.
- Insertion Sort: Efficient for small datasets and nearly sorted arrays.
Non-comparison-based Algorithms:
- Merge Sort: Efficient with a time complexity of O(n log n).
- Quick Sort: Very efficient with an average time complexity of O(n log n).
- Heap Sort: In-place algorithm with a time complexity of O(n log n).
Examples
Bubble Sort
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
Merge Sort
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
L = arr[:mid]
R = arr[mid:]
merge_sort(L)
merge_sort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
return arr
Resources
For more information on sorting algorithms, you can visit our Sorting Algorithms Guide.