diff --git a/merge_sort.py b/merge_sort.py new file mode 100644 index 0000000..bddf5b9 --- /dev/null +++ b/merge_sort.py @@ -0,0 +1,67 @@ +import random +import time + +def merge_sort(nums): + length_of_nums = len(nums) + + if length_of_nums < 2: + return nums + + split = int(length_of_nums / 2) + + split_one = nums[0:split] + split_two = nums[split:] + + sorted_left_side = merge_sort(split_one) + sorted_right_side = merge_sort(split_two) + + return merge(sorted_left_side, sorted_right_side) + + +def merge(first, second): + final = [] + i = 0 + j = 0 + + while i < len(first) and j < len(second): + if first[i] <= second[j]: + final.append(first[i]) + i += 1 + + else: + final.append(second[j]) + j += 1 + + if len(first) > 0: + for item in first[i:]: + final.append(item) + if len(second) > 0: + for item in second[j:]: + final.append(item) + + return final + +# Create a list of random numbers +# The size 80,000 is quite large for Bubble Sort +list_size = 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 +num_list = [random.randint(1, 99999) for _ in range(list_size)] + +print(f"Sorting a list of {list_size} numbers using Merge Sort...") + +# --- Start the timer (using perf_counter for better benchmarking) --- +start_time = time.perf_counter() + +# --- Call the sorting function --- +sorted_list = merge_sort(num_list) # Store the result without printing immediately +# sorted_list = sorted(num_list) + +# --- Stop the timer --- +end_time = time.perf_counter() + +# --- Calculate and print elapsed time --- +elapsed_time = end_time - start_time +print(f"Elapsed time: {elapsed_time:.4f} seconds") + +# --- Optional: Print a small portion of the sorted list to verify --- +print("First 10 elements of sorted list:", sorted_list[:10]) +print("Last 10 elements of sorted list:", sorted_list[-10:]) \ No newline at end of file