Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #gpt-4-0314
- - Max Tokens 4096
- - Temp 1
- #Prompt (empty system prompt)
- >write a python script that will perform a binary merge sort
- ----
- #Output
- Here's an implementation of merge sort algorithm in Python:
- ```python
- def merge_sort(arr):
- if len(arr) <= 1:
- return arr
- # Split the list in half
- middle = len(arr) // 2
- left = arr[:middle]
- right = arr[middle:]
- # Recursively sort both halves
- left_sorted = merge_sort(left)
- right_sorted = merge_sort(right)
- # Merge the two sorted halves
- return binary_merge(left_sorted, right_sorted)
- def binary_merge(left, right):
- result = []
- left_index = 0
- right_index = 0
- while left_index < len(left) and right_index < len(right):
- if left[left_index] < right[right_index]:
- result.append(left[left_index])
- left_index += 1
- else:
- result.append(right[right_index])
- right_index += 1
- # Add the remaining elements from the left and right sublists
- result.extend(left[left_index:])
- result.extend(right[right_index:])
- return result
- # Test the merge_sort function
- arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
- print("Original list:", arr)
- sorted_arr = merge_sort(arr)
- print("Sorted list:", sorted_arr)
- ```
- This script defines a `merge_sort` function that takes a list as input and returns a new list containing the same elements sorted in ascending order using the merge sort algorithm. The `binary_merge` function is a helper function that takes in two sorted lists (`left` and `right`) and merges them into a single sorted list.
- ----
- # Test Output
- Original list: [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
- Sorted list: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
- PASS
Advertisement
Add Comment
Please, Sign In to add comment