Skip to content

Commit abf1f4e

Browse files
authored
Create Merge sort
1 parent a3675f7 commit abf1f4e

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Merge sort

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import os
2+
3+
def merge_sort_files(file_input, file_output):
4+
# Read input file
5+
with open(file_input, 'r') as f:
6+
arr = list(map(int, f.read().split()))
7+
8+
# Sort the array
9+
arr = merge_sort(arr)
10+
11+
# Write sorted data to the output file
12+
with open(file_output, 'w') as f:
13+
f.write(" ".join(map(str, arr)))
14+
15+
def merge_sort(arr):
16+
if len(arr) <= 1:
17+
return arr
18+
19+
mid = len(arr) // 2
20+
left_half = merge_sort(arr[:mid])
21+
right_half = merge_sort(arr[mid:])
22+
23+
return merge(left_half, right_half)
24+
25+
def merge(left, right):
26+
result = []
27+
i = j = 0
28+
while i < len(left) and j < len(right):
29+
if left[i] <= right[j]:
30+
result.append(left[i])
31+
i += 1
32+
else:
33+
result.append(right[j])
34+
j += 1
35+
36+
result.extend(left[i:])
37+
result.extend(right[j:])
38+
return result
39+
40+
# Example usage
41+
input_file = "unsorted.txt"
42+
output_file = "sorted.txt"
43+
merge_sort_files(input_file, output_file)
44+
print(f"Sorted data written to {output_file}")

0 commit comments

Comments
 (0)