File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 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}")
You can’t perform that action at this time.
0 commit comments