[英]how to input n numbers and print it in ascending order without using array
I was trying to create a program that takes n
number of input in a loop and capable of showing output in ascending order. 我试图创建一个程序,该程序在一个循环中接收
n
个输入,并且能够以升序显示输出。 The main theme of program is it should not use arrays. 程序的主要主题是它不应使用数组。
I tried it by creating a program that takes input and shows smallest number first then 2nd smallest and 3rd smallest and so on. 我通过创建一个接受输入并首先显示最小数字,然后显示第二最小和第三最小等等的程序来进行尝试。 But I am new to programming so my program could do only like 1st smallest and it does not work.
但是我是编程的新手,所以我的程序只能像最小的第一个那样工作,并且不起作用。
I also saw heap data structure in one of the similar questions but couldn't figure out how it can work without arrays. 我在类似的问题之一中也看到了堆数据结构,但无法弄清没有数组如何工作。
Please help me how can we use heap data structure or give me a good suggestion to do it. 请帮助我如何使用堆数据结构,或者给我一个很好的建议。
List<Integer> list = new LinkedList<Integer>();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Enter a number, -1 to exit: ");
int num = scanner.nextInt();
if (num == -1) break;
list.add(num);
}
// sort the list (ascending)
Collections.sort(list);
// output the list
for (Integer val : list) {
System.out.println(val);
}
You could use Streams: 您可以使用流:
StreamSupport.stream(
Spliterators.spliteratorUnknownSize(new Scanner(System.in), Spliterator.ORDERED),
false)
.limit(10)
.sorted()
.forEach(System.out::println);
Use SortedSet for default sorting, without duplicates. 使用SortedSet进行默认排序,不重复。 (Don't if duplicates are needed here!)
(如果这里不需要重复!)
SortedSet<Integer> sortedSet = new TreeSet<Integer>();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Enter a number, -1 to exit: ");
int num = scanner.nextInt();
if (num == -1)
break;
sortedSet.add(num);
}
System.out.println(sortedSet);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.