Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Sorting algorithm 1: Bubble Sort
- arr = [19, 5, 14, 17, 13, 19, 15, 11, 3, 9, 1, 7, 2, 13, 19, 5, 10, 6, 4, 5]
- in_order = False
- while not in_order:
- in_order = True
- for i in range(len(arr) - 1):
- if arr[i] > arr[i + 1]:
- temp = arr[i]
- arr[i] = arr[i + 1]
- arr[i + 1] = temp
- in_order = False
- print(arr)
- # Sorting algorithm 2: Insertion sort
- arr = [10, 15, 8, 18, 12, 15, 11, 5, 4, 2, 4, 10, 18, 5, 13, 4, 1, 12, 5, 9]
- sorted_arr = []
- for _ in range(len(arr)):
- minimum = arr[0]
- for i in arr:
- if i < minimum:
- minimum = i
- sorted_arr.append(minimum)
- arr.remove(minimum)
- print(sorted_arr)
- # Merging sorted arrays into one larger array
- def merge(arr1, arr2):
- new_arr = []
- first_at = 0
- second_at = 0
- while first_at < len(arr1) or second_at < len(arr2):
- if second_at >= len(arr2):
- new_arr.append(arr1[first_at])
- first_at += 1
- continue
- if first_at >= len(arr1):
- new_arr.append(arr2[second_at])
- second_at += 1
- continue
- if arr1[first_at] < arr2[second_at]:
- new_arr.append(arr1[first_at])
- first_at += 1
- else:
- new_arr.append(arr2[second_at])
- second_at += 1
- return new_arr
- # Sorting algorithm 3: Merge sort
- arr = [19, 8, 11, 14, 13, 13, 11, 15, 4, 10, 19, 6, 11, 6, 19, 6, 16, 8, 15, 5]
- sub_len = 1
- while sub_len < len(arr):
- for left_start in range(0, len(arr), 2 * sub_len):
- # Define the left segment of the array to merge
- left = left_start
- left_end = min(left + sub_len, len(arr)) # the end is not inclusive
- # Now define the right part as well
- right = left_end
- right_end = min(right + sub_len, len(arr))
- # Merge the left and right ends, and put them back into the array
- arr[left:right_end] = merge(arr[left:left_end], arr[right:right_end])
- sub_len *= 2
- print(arr)
Add Comment
Please, Sign In to add comment