简体   繁体   English

如何在没有 arrays 的情况下对数字进行排序

[英]how to sort numbers without arrays

I want to sort numbers without using Arrays .我想在不使用 Arrays的情况下对数字进行排序。 I have this:我有这个:

 Scanner s = new Scanner(System.in);
    System.out.print("Input 3 numbers: ");
    int a = s.nextInt();
    int b = s.nextInt();
    int c = s.nextInt();

    System.out.print("Increscent: ");

    if (a >= b) { 
        int temp; 

        temp = a;
        a = b;
        b = temp;
    }

    if (c < a) 
    {
        System.out.println(c + " " + a + " " + b);
    } else if (c > b) 
    {
        System.out.println(a + " " + b + " " + c);
    } else 
    {
        System.out.println(a + " " + c + " " + b);
    }

But what should I do if I want to use more numbers?但是如果我想使用更多的数字怎么办? Is there some better code or I must use this way all the time?有没有更好的代码或者我必须一直使用这种方式?

The purpose of arrays are so that you can have multiple of similar data. arrays 的目的是让您可以拥有多个相似的数据。 Like an integer. In hindsight you could probably place hundreds of variables, or you can do it on one line.就像 integer。事后看来,您可能会放置数百个变量,或者您可以在一行中完成。

what do you think is better?你觉得什么更好?

int a;
int b;
int c;
int d;

or或者

int a[];

There are methods to have many arguments for example like varargs, for functions.有很多方法可以有很多 arguments 例如像 varargs,用于函数。 But in the long run those work like arrays anyways.但从长远来看,无论如何这些都像 arrays 一样工作。

For terms of sorting algorithsm, there are hundreds of different sorting agorithms, and around a few super common ones.对于排序算法而言,有数百种不同的排序算法,以及一些非常常见的排序算法。

varargs An example of use of varargs in C varargs 在 C 中使用 varargs 的例子

sorting algorithms https://en.wikipedia.org/wiki/Sorting_algorithm排序算法https://en.wikipedia.org/wiki/Sorting_algorithm

edit: Just realized this was Java, but the same theory applies Java variadic function parameters编辑:刚刚意识到这是 Java,但同样的理论适用于Java 可变参数 function 参数

Well, you can do something close to this: Sort 4 numbers without array好吧,你可以做一些类似的事情: Sort 4 numbers without array

Let me help you:让我帮帮你:

int tmp;

if (a > b) { tmp = a; a = b; b = tmp; }
if (a > c) { tmp = a; a = c; c = tmp; }
if (b > c) { tmp = b; b = c; c = tmp; }

System.out.println(a + " " + b + " " + c);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM