Я пытаюсь отсортировать очередь (реализована с использованием связанного списка) с использованием другой очереди (также реализованной с использованием связанного списка), но по той или иной причине я не получаю желаемый результат, пожалуйста, помогите мне.
public class Source
{
public static void main(String args[])
{
Queue<Integer> queue = new LinkedList<Integer>();
Scanner s = new Scanner(System.in);
int n = s.nextInt();
for(int i=0;i<n;i++)
{
queue.add(s.nextInt());
}
System.out.print(sort(queue));
}
// Method to sort the queue
static Queue sort(Queue<Integer> queue)
{
Queue<Integer> NewQueue = new LinkedList<Integer>();
if(!queue.isEmpty())
{
NewQueue.add(queue.remove()); // To add the first element in the NewQueue
}else {
return queue.poll(); // return null if given queue is empty
}
while(!queue.isEmpty())
{
int temp = queue.remove();
if(!NewQueue.isEmpty() && NewQueue.peek()=<temp) // Add if the element is smaller
{ // than peek element
NewQueue.add(temp);
}else if(!NewQueue.isEmpty() && NewQueue.peek()>temp) // Other Wise
{
NewQueue.add(temp);
while(!NewQueue.isEmpty() && NewQueue.peek()>temp) // Keep removing from front adding at
{ rear till temp itself comes for the check
NewQueue.add(NewQueue.remove());
}
}else if(NewQueue.isEmpty())
{
NewQueue.add(temp);
}
}
return NewQueue;
}
}
Я дал ему ввод 12 6 12 3 4 5 1 7 8 10 9 11 2
И он дал результат 1, 3, 6, 12, 4, 5, 7, 8, 10, 9, 11, 2 Вместо 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12