问题描述
我正在尝试使用递归方法对队列进行排序(以升序排列)。输入由用户输入。 下面的这个没有给我正确的输出。例如:12.元素:6 12 3 4 5 1 7 8 10 9 11 2,结果:2 11 9 10 8 7 1 5 4 3 12 6,这是不正确的。我试图找出哪一部分不正确。我不想更改main方法中的任何内容。
import java.util.*;
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();
while (n-- > 0)
queue.add(s.nextInt());
sort(queue);
}
static void FrontToLast(Queue<Integer> queue,int qsize) {
if (qsize <= 0) {
return;
}
queue.add(queue.peek());
queue.remove();
FrontToLast(queue,qsize - 1);
}
static void pushInQueue(Queue<Integer> queue,int temp,int qsize) {
if (queue.isEmpty() || qsize == 0)
{
queue.add(temp);
return;
}
else if (temp <= queue.peek())
{
queue.add(temp);
FrontToLast(queue,qsize);
}
else
{
queue.add(queue.peek());
queue.remove();
pushInQueue(queue,temp,qsize - 1);
}
}
static void sort(Queue<Integer> queue) {
if (queue.isEmpty()) {
return;
}
int temp = queue.peek();
queue.remove();
sort(queue);
pushInQueue(queue,queue.size());
while (!queue.isEmpty())
{
System.out.print(queue.peek() + " ");
queue.remove();
}
}
}
解决方法
import java.util.LinkedList;
import java.util.Queue; 导入java.util.Scanner;
公共类来源{ 静态队列queue = new LinkedList(); //更改
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
while (n-- > 0)
queue.add(s.nextInt());
sort(queue);
System.out.println("Final Result : " + queue); // changed
}
static void FrontToLast(Queue<Integer> queue,int qsize) {
if (qsize <= 0) {
return;
}
queue.add(queue.peek());
queue.remove();
FrontToLast(queue,qsize - 1);
}
static void pushInQueue(Queue<Integer> queue,int temp,int qsize) {
if (queue.isEmpty() || qsize == 0) {
queue.add(temp);
return;
} else if (temp <= queue.peek()) {
queue.add(temp);
FrontToLast(queue,qsize);
} else {
queue.add(queue.peek());
queue.remove();
pushInQueue(queue,temp,qsize - 1);
}
}
static void sort(Queue<Integer> queue) {
if (queue.isEmpty()) {
return;
}
int temp = queue.peek();
queue.remove();
sort(queue);
pushInQueue(queue,queue.size());
/*
* while (!queue.isEmpty()) { System.out.print(queue.peek() + " ");
* queue.remove(); }
*/
}
}