文件排序

1MB内存下文件排序
本文介绍了一种在仅有1MB内存限制下进行文件排序的方法。该方法适用于存储单一数字的文件,并假设数字不重复且无附加信息。通过位操作实现高效排序,最终将排序后的结果写入新文件。

前提:

 * 文件排序 

 * 文件中每行保存一个数字

 * 数字没有重复的

 * 没有其他相关的信息与数字想关联 

 * 大概只有1M的内存空间可以使用

 

代码

package com.wutianyi.interesting;

 

import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

 

 

/**

 * @author hanjie.wuhj 

 * 文件排序 

 * 文件中每行保存一个数字

 * 数字没有重复的

 * 没有其他相关的信息与数字想关联 

 * 大概只有1M的内存空间可以使用

 */

public class FileSort {

 

/**

* 1MB的内存

*/

byte[] results = new byte[1024 * 1024];

byte[] values = new byte[] { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, -128 };

 

void createSortFile(String file) {

PrintWriter pw = null;

try {

pw = new PrintWriter(new File(file));

int value = 1024 * 1024 * 8 - 1;

for (int i = value; i >= 0; i--) {

pw.println(i);

}

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} finally {

if (null != pw) {

pw.close();

}

}

 

}

 

void sortFile(String file) {

BufferedReader reader = null;

try {

reader = new BufferedReader(new InputStreamReader(

new FileInputStream(file)));

 

String line = reader.readLine();

while (null != line && !line.isEmpty()) {

int v = Integer.parseInt(line);

dealValue(v);

line = reader.readLine();

}

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

if (null != reader) {

try {

reader.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

 

}

 

void dealValue(int v) {

int index = v / 8;

int position = v % 8;

 

results[index] = (byte) (results[index] | values[position]);

 

}

 

void printValue(String out) {

PrintWriter pw = null;

try {

pw = new PrintWriter(new File(out));

int i = 0;

int index = 1;

for (byte result : results) {

for (int j = 0; j < 8; j++) {

if ((result & values[j]) == values[j]) {

pw.println(i + j);

}

}

i = index * 8;

++index;

}

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} finally {

if (null != pw) {

pw.flush();

pw.close();

}

}

}

 

public static void main(String[] args) {

FileSort sort = new FileSort();

// sort.createSortFile("sort=original.txt");

long start = System.currentTimeMillis();

sort.sortFile("sort=original.txt");

long end_1 = System.currentTimeMillis();

System.out.println("sort time: " + (end_1 - start));

sort.printValue("sort-result.txt");

long end_2 = System.currentTimeMillis();

System.out.println("writer file time: " + (end_2 - end_1));

}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值