简体   繁体   中英

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. I can't think of any approach to solve this other than using an 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. A java int occupies 4 bytes, so every file position will be a four fold.

So you could use arrays . If an array for all, Arrays.sort would solve it. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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