编程珠玑:10^7个正整数文件排序

来源:互联网 发布:ug电极编程视频 编辑:程序博客网 时间:2024/06/07 04:50

昨天看《编程珠玑》看见这个问题,又恰好自学Java,看到《Java编程思想》中的IO章节,就分别用Java中的io和nio方式将其位图结构排序实现了下

PS:没有按照它的内存约束要求

位图结构排序:

package Pearls;import java.util.*;import java.io.*;import java.nio.*;import java.nio.channels.*;abstract class Tester{static final int DATASIZE=10000000;String name;Tester(String name){this.name=name;}public void runTest() throws Exception{long startTime = System.currentTimeMillis();  test();long endTime = System.currentTimeMillis(); //输出使用方法和运行时间System.out.println(name+":\n程序运行时间:" + (endTime - startTime) + "ms");//内存使用情况查看,不知这样查看对不对,网上找的Runtime rt = Runtime.getRuntime();long total_mem = rt.totalMemory();long free_mem = rt.freeMemory();long used_mem = total_mem - free_mem;System.out.println("Amount of used memory: " + used_mem/1024/1024+"M");}abstract void test() throws IOException;}public class BitSort {                                                                                                                     public static void main(String[] args) throws Exception  {Tester f1=new Tester("Buffered"){ public void test() throws IOException {//位图设置 BitSet bm=new BitSet(DATASIZE);  bm.clear();//数据输入设置DataInputStream br= new DataInputStream(new BufferedInputStream(new FileInputStream("./src/Pearls/data.txt")));        for(int i=0;i<DATASIZE;i++){        bm.set(br.readInt(), true);        }        br.close();        FileOutputStream fw=new FileOutputStream("./src/Pearls/datas.txt");DataOutputStream dw=new DataOutputStream(new BufferedOutputStream(fw));for(int i=0;i<DATASIZE;i++){        if(bm.get(i))        dw.writeInt(i);        }dw.close();}};f1.runTest();    Tester f2=new Tester("Mapped"){    public void test() throws IOException{    //位图设置 BitSet bm=new BitSet(DATASIZE);  bm.clear();        FileChannel fc=new FileInputStream("./src/Pearls/data.txt").getChannel();        IntBuffer ib=fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()).asIntBuffer();        long size=fc.size();            for(int i=0;i<DATASIZE;i++){            bm.set(ib.get(), true);            }            fc.close();                                        FileChannel fc2=new RandomAccessFile("./src/Pearls/data2s.txt","rw")                           .getChannel();    IntBuffer ibw=fc2.map(FileChannel.MapMode.READ_WRITE,0,size)             .asIntBuffer();    for(int i=0;i<DATASIZE;i++){            if(bm.get(i))            ibw.put(i);            }    fc2.close();    }    };    f2.runTest();}}
输出结果:

Buffered:
程序运行时间:3820ms
Amount of used memory: 3M
Mapped:
程序运行时间:189ms
Amount of used memory: 4M

0 0
原创粉丝点击