外部排序

 External sorting is required when the data being sorted do not fit into the main memory of a computing device (usually RAM ) and instead they must reside in the slower external memory (usually a hard drive ). External sorting typicallyuses a hybrid sort-merge strategy. In the sorting phase, chunks of data small enough to fit in main memory are read, sorted, and written out to a temporary file. In themerge phase, the sorted subfiles are combined into a single larger file. (External sorting WIKI


One example of external sorting is the external merge sort algorithm, which sorts chunksthat each fit in RAM, then merges the sorted chunks together. We first divide the file intoruns such that the size of a run is small enough to fit into main memory. Then sort each run in main memory using merge sort sorting algorithm. Finally merge the resulting runs together into successively bigger runs, until the file is sorted.

Prerequisite for the algorithm/code:
MergeSort : Used for sort individual runs (a run is part of file that is small enough to fit in main memory)
Merge K Sorted Arrays : Used to merge sorted runs.

Implemetation from geeksforgeeks


How to do:

1. 内存中分配一个极小的 Buffer,将大文件 input.txt 按行读入,读取到 buffer 大小 或者 大文件读完时,对 Buffer 中的数据调用内排进行排序(归并排序,时间复杂度O(nlogn) ),排序后将有序序列写入磁盘文件(0,1....,9)。

2. 9-way merge 有序文件(最小堆排序:root 最小值写到 output.txt )到一个大文件 output.txt



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
外部排序是一种用于处理大型文件的排序算法,由于文件太大无法全部读入内存,因此需要将文件分割成多个部分,分别进行排序后再合并。下面是一种基于归并排序外部排序实现: 1. 首先将大文件分割成多个小文件,每个小文件的大小可以根据内存的大小来决定,一般选择小于内存容量的值。 2. 对每个小文件进行排序,可以使用内置的sort函数或其他快速排序算法。 3. 将排序后的小文件依次读入内存,进行归并排序,生成一个有序的大文件。 4. 重复步骤1-3,直到所有小文件都已经排序并合并成一个大文件。 下面是一个简单的Python实现: ```python import heapq import os def external_sort(input_file, output_file, chunk_size=1000000): """外部排序""" chunks = [] with open(input_file, 'rb') as f: while True: chunk = f.read(chunk_size) if not chunk: break chunk = list(map(int, chunk.split())) chunk.sort() chunks.append(chunk) with open(output_file, 'wb') as f: for item in heapq.merge(*chunks): f.write('{} '.format(item).encode()) # 删除临时文件 for chunk_file in chunks: os.remove(chunk_file) if __name__ == '__main__': external_sort('big_file.txt', 'sorted_file.txt') ``` 这个实现中,我们将大文件分割成大小为`chunk_size`的小文件,每个小文件进行排序后,再将它们依次读入内存,使用heapq.merge函数进行归并排序,最后生成一个有序的大文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值