2

I have a class, "Segment" through which I get values of 2 arrays. my main method is

public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        Segment[] segments = new Segment[n];
        for (int i = 0; i < n; i++) {
            int start, end;
            start = scanner.nextInt();
            end = scanner.nextInt();
            segments[i] = new Segment(start, end);
        }
}

class of Segment is like below.

 private static class Segment  {

        int start, end;

        Segment() {
        }

        Segment(int start, int end) {
            this.start = start;
            this.end = end;
        }
}

Now, how to sort segments with respect to end point.

  • "Segment" through which I get values of 2 arrays." Is start and end are array ? Any specific reason to declare class as static ? – sauumum Jun 13 '16 at 15:13

3 Answers3

2

For sorting use Arrays.sort and implement a Comparator.

Arrays.sort(segments, new Comparator<Segment>() {
    @Override
    public int compare(Segment o1, Segment o2) {
        return Integer.compare(o1.getEnd(), o2.getEnd());
    }
});
wake-0
  • 3,918
  • 5
  • 28
  • 45
1

You can have Segment implement Comparable:

private static class Segment implements Comparable<Segment> {
    int start, end;
    Segment() {
    }
    Segment(int start, int end) {
        this.start = start;
        this.end = end;
    }
    @Override
    public int compareTo(Segment otherSegment) {
        int result = 0;
        if (start != otherSegment.start) {
            result = start < otherSegment.start ? -1 : 1;
        }
        return result;
    }
    @Override
    public String toString() {
        return "Segment [start=" + start + ", end=" + end + "]";
    }
}

I changed your array to a List, and used Collections to sort:

Collections.sort(segments);

Your modified code:

    Scanner scanner = new Scanner(System.in);
    int n = scanner.nextInt();
    List<Segment> segments = new ArrayList<Segment>();
    for (int i = 0; i < n; i++) {
        int start, end;
        start = scanner.nextInt();
        end = scanner.nextInt();
        segments.add(new Segment(start, end));
    }

    Collections.sort(segments);
    System.out.println(segments);

Insert your sorting logic in the compareTo method. This is similar to using a Comparator, the difference is simply whether you want the sorting logic to be in Segment or in a utility class.

alexbt
  • 16,415
  • 6
  • 78
  • 87
0

you have to make the Segement class implement the Comparable interface and override the compareTo() method then use : Segements.sort() // to sort it.