Search code examples
javasortingnumbers

how to sort numbers without arrays


I want to sort numbers without using 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?


Solution

  • Well, you can do something close to this: 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);