feat: implement sorting algorithms in Python

This commit is contained in:
2026-04-12 03:00:46 +03:30
commit d0b7968cb2
5 changed files with 114 additions and 0 deletions
+42
View File
@@ -0,0 +1,42 @@
def merge_sort(arr):
# If the array length is less than 2, no sorting is needed
if len(arr) <= 1:
return arr
# Find the middle of the array
mid = len(arr) // 2
# Divide the array into two halves
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
# Merge two sorted halves
return merge(left_half, right_half)
def merge(left, right):
result = []
i = j = 0
# As long as there are elements left in both lists
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
# Add the remaining elements (one of the lists may run out early)
result.extend(left[i:])
result.extend(right[j:])
return result
# Example:
nums = [5, 2, 4, 6, 1, 3]
print("Before sorting:", nums)
nums = merge_sort(nums)
print("After sorting:", nums)