0

I want to print the arrays in a queue but in ascending, numerical order.

For instance, queue contains

{3, 5},
{4, 5}, 
{0, 4}, 
{3, 4}, 
{4, 6}

How would I make it print as follows?

{0, 4}, 
{3, 4}, 
{3, 5}, 
{4, 5}, 
{4, 6}

I also checked, but I can't seem to find a way to push an array back into the queue from like the front?

I would appreciate any tips or help.

This is what I tried, but it doesn't work:

while (queue.size() > 0) {
  int[] current = queue.remove();
  int[] current1 = queue.peek();
  
  if (queue.size()!=0) {
    if (current[0]>current1[0]) {
      int[] holdarr = current;
      current = queue.remove();
      queue.add(holdarr);
    } else if (current[0] == current1[0] & current[1]>current1[1]) {
      int[] holdarr = current;
      current = queue.remove();
      queue.add(holdarr);
    }
  }
  
  System.out.println(current[0] + ", " + current[1]);
6
  • 2
    What type is queue? Commented Oct 15, 2021 at 7:23
  • 1
    For sorting, you need to implement (or use) a sorting algorithm. All sort algorithms take longer than linear time (on average). If your queue does not support random access, it will be best to just consume the entire queue and put the contents in an array or List that you can sort efficiently. Commented Oct 15, 2021 at 7:34
  • Hint: Your algorithm prints the first element if it is smaller than the second one, but what if the third would be even smaller? Commented Oct 15, 2021 at 7:41
  • oh i see! in the end, i decided to just put everything into a matrix to sort but i was just wondering if i could sort it since my values were already in a queue... thanks tho! @Hulk Commented Oct 15, 2021 at 7:56
  • Does this answer your question? Java: Sorting a queue Commented Oct 15, 2021 at 8:18

1 Answer 1

0

Try this.

public static void main(String[] args) {
    int[][] a = {
        {3, 5},
        {4, 5},
        {0, 4},
        {3, 4},
        {4, 6}};
    Queue<int[]> que = new ArrayDeque<>();
    for (int[] e : a)
        que.add(e);

    que.stream()
        .sorted(Arrays::compare)
        .forEach(e -> System.out.println(Arrays.toString(e)));
}

output:

[0, 4]
[3, 4]
[3, 5]
[4, 5]
[4, 6]
Sign up to request clarification or add additional context in comments.

1 Comment

ooo i'll try it out! thankss!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.