简体   繁体   English

不使用集合Java对文件中的整数排序

[英]Sorting integers in a file without using collections java

I need to sort integers in a file without using an array/arraylist. 我需要在不使用数组/数组列表的情况下对文件中的整数进行排序。 The file has to be read using RandomAccessFile. 必须使用RandomAccessFile读取文件。 I can't think of any approach to solve this other than using an arraylist. 除了使用arraylist之外,我想不出其他任何方法来解决此问题。 I am allowed to use a few variables. 我可以使用一些变量。 Also, how do i swap two numbers in a file? 另外,如何在文件中交换两个数字?

import java.io.*;

class Sort
{
    public static void main(String[] args)
    {
        try {
            RandomAccessFile abc = new RandomAccessFile(args[0], "rw");
            long n = abc.length();
            System.out.println(n);
            long i = 0;
            while (i <= n) {
                System.out.println("Coming Here");
                int c = Integer.parseInt(abc.readUTF());
                System.out.println(c);
                i = i + 1;
            }
        } catch (IOException e) {
            System.out.println(e);
        }
    }
}

First of all the task would be difficult when the integers where text in the file, due to varying lengths of textual number representations. 首先,由于整数数字表示长度的变化,当整数在文件中的文本位置时,任务将很困难。

  • First it should be checked that the data is binary. 首先,应检查数据是否为二进制。

So I'll assume that binary data, containing int is stored in the file. 因此,我假设包含int二进制数据存储在文件中。 A java int occupies 4 bytes, so every file position will be a four fold. 一个java int占用4个字节,因此每个文件位置将是4倍。

So you could use arrays . 所以你可以使用数组 If an array for all, Arrays.sort would solve it. 如果为所有数组,则Arrays.sort会解决。 Otherwise several arrays and a merge sort algorithm would be feasible. 否则,几个数组和合并排序算法将是可行的。

Staying with a random access file you could do quicksort or merge sort using: 使用随机访问文件,您可以使用以下方法进行快速排序或合并排序:

fh.seek(i1*4L);
int n1 = fh.readInt();
// If ints are not stored in big endian byte order:
// int n1littleEndian = Integer.reverse(n1);

In production environment, one would get the associated channel, and use a memory mapped byte buffer; 在生产环境中,将获取关联的通道,并使用内存映射的字节缓冲区; to speed up things. 加快速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM