Advertisement
plarmi

Sorting Methods

Sep 14th, 2023
834
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.48 KB | None | 0 0
  1. array = [5, 1, 3, 10, 11, -1, 0, -5, 50, 20, 17, 12, 12, 2, 12]
  2.  
  3. def bubble_sort(array):
  4.     n = len(array)
  5.     for i in range(n):
  6.         swapped = False
  7.         for j in range(0, n - i - 1):
  8.             if array[j] > array[j + 1]:
  9.                 array[j], array[j + 1] = array[j + 1], array[j]
  10.                 swapped = True
  11.  
  12.         if not swapped:
  13.             print("Список уже отсортирован!")
  14.             break
  15.  
  16.  
  17. def insertion(list_nums):
  18.     for i in range(1, len(list_nums)):
  19.         item = list_nums[i]
  20.         i2 = i - 1
  21.         while i2 >= 0 and list_nums[i2] > item:
  22.             list_nums[i2 + 1] = list_nums[i2]
  23.             i2 -= 1
  24.             print(array)
  25.         list_nums[i2 + 1] = item
  26.  
  27.  
  28. def merge_sort(arr):
  29.     if len(arr) <= 1:
  30.         return arr
  31.  
  32.     mid = len(arr) // 2
  33.     left_half = arr[:mid]
  34.     right_half = arr[mid:]
  35.  
  36.     left_half = merge_sort(left_half)
  37.     right_half = merge_sort(right_half)
  38.  
  39.     sorted_arr = merge(left_half, right_half)
  40.  
  41.     return sorted_arr
  42.  
  43.  
  44. def merge(left, right):
  45.     result = []
  46.     left_index, right_index = 0, 0
  47.  
  48.     while left_index < len(left) and right_index < len(right):
  49.         if left[left_index] < right[right_index]:
  50.             result.append(left[left_index])
  51.             left_index += 1
  52.         else:
  53.             result.append(right[right_index])
  54.             right_index += 1
  55.  
  56.     result.extend(left[left_index:])
  57.     result.extend(right[right_index:])
  58.  
  59.     return result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement