Home > database >  Log sorting - Custom sorting is not working
Log sorting - Custom sorting is not working

Time:01-03

Trying to sort the array 0f log versions in ascending order. I can get it to work by directly implementing Comparator as

 Arrays.sort(input, new CustomComparator())

and writing the same logic as below code(from the Parse class) in the CustomComparator class. However, when i try to sort it by adding the values in a Queue, the sorting does not work.

import java.util.*;

public class LogSorting {

    public static void main(String[] args) {
        String[] input = {"2.10.0", "1.0.100", "1.0.1", "1.1.100", "2.1.10", "1.1.1"};
        PriorityQueue<Parse> str = new PriorityQueue<>();
        for (String i : input) {
            String[] result = i.split("\\.");
            str.add(new Parse(Integer.parseInt(result[0]), Integer.parseInt(result[1]), Integer.parseInt(result[2])));
        }
        for (Parse p : str) {
            System.out.println(p.major   " "   p.minor   " "   p.patch);
        }
    }
}

class Parse implements Comparable<Parse> {
    int major;
    int minor;
    int patch;

    Parse(int major, int minor, int patch) {
        this.major = major;
        this.minor = minor;
        this.patch = patch;
    }

    public int compareTo(Parse p) {

        if (major == p.major && minor == p.minor)
            return Integer.compare(patch, p.patch);
        if (major == p.major)
            return Integer.compare(minor, p.minor);
        return Integer.compare(major, p.major);
    }
}

output

1 0 1

1 1 100

1 0 100

2 10 0

2 1 10

1 1 1

The output should be sorted as 1 0 1, 1 0 100, 1 1 1, 1 1 100, 2 1 10, 2 10 0

CodePudding user response:

It's not a sorted array, so that you can just go from one element to the one with the lesser priority.The Iterator provided in method iterator() is not guaranteed to traverse the elements of the PriorityQueue in any particular order. If you need ordered traversal, consider using

Arrays.sort(pq.toArray()).

Or you can

    while (!str.isEmpty()) {
        Parse p = str.peek();
        str.remove();
        System.out.println(p.major   " "   p.minor   " "   p.patch);
    }

But this will empty the queue.

I do now know why are you using priority queue. If you just want sorted list then use List and then sort the list using comparable/comparator.

  • Related