Types of Sorting and Searching in Python
Types of Sorting and Searching in Python
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
python
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
return arr
python
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
• Quick Sort: Often faster in practice than other O(n(n) log n))
algorithms on average, quick sort uses a pivot to partition the
array into elements less than the pivot and greater than it, then
recursively sorts the sub-arrays. However, its worst-case
performance is O(n²).
• Heap Sort: Converts the list into a heap data structure, then
repeatedly extracts the maximum (or minimum) element to
build a sorted list in O(n log n) time.
• Shell Sort: An optimized version of insertion sort that allows
elements to move over larger gaps, thereby reducing the
number of swaps.
data = [5, 3, 7, 1, 9]
print(linear_search(data, 7)) # Outputs 2
python
def binary_search(arr, target):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
data = [1, 3, 5, 7, 9]
print(binary_search(data, 7)) # Outputs 3
In Summary
Python’s ecosystem supports both simple and complex schemes
for sorting and searching: