SansPapyrus683

Python Sorting Algorithms

Dec 2nd, 2021 (edited)
697
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # Sorting algorithm 1: Bubble Sort
  2. arr = [19, 5, 14, 17, 13, 19, 15, 11, 3, 9, 1, 7, 2, 13, 19, 5, 10, 6, 4, 5]
  3. in_order = False
  4. while not in_order:
  5.     in_order = True
  6.     for i in range(len(arr) - 1):
  7.         if arr[i] > arr[i + 1]:
  8.             temp = arr[i]
  9.             arr[i] = arr[i + 1]
  10.             arr[i + 1] = temp
  11.             in_order = False
  12. print(arr)
  13.  
  14. # Sorting algorithm 2: Insertion sort
  15. arr = [10, 15, 8, 18, 12, 15, 11, 5, 4, 2, 4, 10, 18, 5, 13, 4, 1, 12, 5, 9]
  16. sorted_arr = []
  17. for _ in range(len(arr)):
  18.     minimum = arr[0]
  19.     for i in arr:
  20.         if i < minimum:
  21.             minimum = i
  22.     sorted_arr.append(minimum)
  23.     arr.remove(minimum)
  24. print(sorted_arr)
  25.  
  26.  
  27. # Merging sorted arrays into one larger array
  28. def merge(arr1, arr2):
  29.     new_arr = []
  30.     first_at = 0
  31.     second_at = 0
  32.     while first_at < len(arr1) or second_at < len(arr2):
  33.         if second_at >= len(arr2):
  34.             new_arr.append(arr1[first_at])
  35.             first_at += 1
  36.             continue
  37.         if first_at >= len(arr1):
  38.             new_arr.append(arr2[second_at])
  39.             second_at += 1
  40.             continue
  41.  
  42.         if arr1[first_at] < arr2[second_at]:
  43.             new_arr.append(arr1[first_at])
  44.             first_at += 1
  45.         else:
  46.             new_arr.append(arr2[second_at])
  47.             second_at += 1
  48.     return new_arr
  49.  
  50.  
  51. # Sorting algorithm 3: Merge sort
  52. arr = [19, 8, 11, 14, 13, 13, 11, 15, 4, 10, 19, 6, 11, 6, 19, 6, 16, 8, 15, 5]
  53. sub_len = 1
  54. while sub_len < len(arr):
  55.     for left_start in range(0, len(arr), 2 * sub_len):
  56.         # Define the left segment of the array to merge
  57.         left = left_start
  58.         left_end = min(left + sub_len, len(arr))  # the end is not inclusive
  59.         # Now define the right part as well
  60.         right = left_end
  61.         right_end = min(right + sub_len, len(arr))
  62.         # Merge the left and right ends, and put them back into the array
  63.         arr[left:right_end] = merge(arr[left:left_end], arr[right:right_end])
  64.     sub_len *= 2
  65. print(arr)
  66.  
RAW Paste Data