简体   繁体   中英

Java: Sorting integer digits from greatest to least

I need help sorting the integer digits from greatest to least using if-statements only WITHOUT using String/Arrays or anything of the sort. Assume I have already initialized and imported Scanner and keyboard to allow for input. The issue I'm having is with the if-statements as I cannot seem to get it right. Please help, I have been trying to work on this for the last 5 hours. Thanks :)

    System.out.print("Enter a five digit integer number: ");

    int fiveInt, digit1, digit2, digit3, digit4, digit5; //Declaring variables

    Scanner keyboard = new Scanner (System.in);

    fiveInt = keyboard.nextInt(); //User input will be required



    System.out.println(" "); //Prints empty line


    //The following will be explained assuming number entered was 12345.
    //The (int) will change whatever result of the division taking place to an integer.

    digit1 = (int)(fiveInt / 10000); //12345 divided by 10000 = 1.2345 converted to 1 due to (int).
    digit2 = ((int)(fiveInt / 1000)) - (digit1 * 10); //12345 divided by 1000 = 12.345 - (1 * 10) = 2.345 converted 2 due to (int).
    digit3 = ((int)(fiveInt / 100)) - (digit1 * 100) - (digit2 * 10); //12345 divided by 100 = 123.45 - (1*100) - (2*10) = 3.45 converted to 3 due to (int).
    digit4 = ((int)(fiveInt / 10)) - (digit1 * 1000) - (digit2 * 100) - (digit3 * 10); //12345 divided by 10 = 1234.5 - (1*1000) - (2*100) - (3*10) = 4.5 converted to 4 due to (int).
    digit5 = fiveInt - (digit1 * 10000) - (digit2 * 1000) - (digit3 * 100) - (digit4 * 10); //12345 - (1*10000) - (2*1000) - (3*100) - (4*10) = 5



    System.out.println("The digits in " + fiveInt + " are: " + digit1 + ", " + digit2 + ", " + digit3 + ", " + digit4 + ", " + digit5);

    System.out.println(" "); //Prints empty line




    //Insert explanation for lines of code below here.



    if(digit1 < digit2){
      int a = digit1;
      digit1 = digit2;
      digit2 = digit1;
    }

    if(digit1 < digit3){
      int b = digit1;
      digit1 = digit3;
      digit3 = digit1;
    }

    if(digit1 < digit4){
      int c = digit1;
      digit1 = digit4;
      digit4 = digit1;
    }

    if(digit1 < digit5){
      int d = digit1;
      digit1 = digit5;
      digit5 = digit1;
    }




    //Insert explanation for lines of code above here.





    System.out.print("The largest number with these digits is: " + digit1 + digit2 + digit3 + digit4 + digit5); //Displays the digits in their sorted mann

a first error is that you're not restoring the variable you temporanely store in a , b , c ...Instead of

if(digit1 < digit2){
      int a = digit1;
      digit1 = digit2;
      digit2 = digit1;
    }

You probably want:

if(digit1 < digit2){
      int a = digit1;
      digit1 = digit2;
      digit2 = a;
    }

Anyway, this won't be enought, since algorithm won't 'sort' the five variables. With this code, you'll simply have the greatest digit stored in digit1 .

If what you want is real sorting, the easiest way is to put integers in an array and sort it using Arrays.sort()

Also, your last line of code:

System.out.print("The largest number with these digits is: " + digit1 + digit2 + digit3 + digit4 + digit5);

won't print sorted integers, but a sum of the digits (15 in your example)

您需要定义5个项目,例如a1,a2,a3,a4,a5,然后找到最大或最小排序的项目

This is elaboration of what I just wrote. Basically you have to get 5 ints ( a1 to a5) and returns sorted values in them. I first find the order. For example in the following test data 7 is the 3rd item. Then put 7 and others in the appropriate order of predefined ints I mentioned from a1 to a5 and print them out ...

public class B{

static int a1, a2, a3, a4, a5;

static int digit1=4;
static int digit2=1;
static int digit3=7;
static int digit4=9;
static int digit5=5;

public static void main(String args[]) {


    setDigitOrer(digit1, getOrder(digit1, digit2, digit3, digit4, digit5));
    setDigitOrer(digit2, getOrder(digit2, digit1, digit3, digit4, digit5));
    setDigitOrer(digit3, getOrder(digit3, digit2, digit1, digit4, digit5));
    setDigitOrer(digit4, getOrder(digit4, digit2, digit3, digit1, digit5));
    setDigitOrer(digit5, getOrder(digit5, digit2, digit3, digit4, digit1));


    System.out.println(a1 );
    System.out.println(a2 );
    System.out.println(a3 );
    System.out.println(a4 );
    System.out.println(a5 );

}

private static void setDigitOrer(int digit, int digitOrder) {
    if (digitOrder == 0){
        a1 = digit;
    } else if (digitOrder == 1){
        a2 = digit;
    } else if (digitOrder == 2){
        a3 = digit;
    } else if (digitOrder == 3){
        a4 = digit;
    } else if (digitOrder == 4){
        a5 = digit;
    }

}

private static int getOrder(int digit, int... digits){
    int count = 0;
    for (int d: digits){
        if (d > digit){
            count++;
        }
    }
    return count;
}

}

result is 9 7 5 4 1

This is definitely homework and the rules are not that clear. However, I am sure that the solution does not include 4 calls to the Math.min or Math.max method. Use your head and look up some sorting algorithms and try to implement one.

Use the following small python program:

for pos in range(1,5):
    for num in range(1,6-pos):
        print "if (digit%d < digit%d) {" % (num, num+1)
        print "\tSystem.out.println(\"Swapping \"+digit%d+\" and \"+digit%d);" % (num, num+1)
        print "\tint temp=digit%d;" % (num)
        print "\tdigit%d=digit%d;" % (num, num+1)
        print "\tdigit%d=temp;" % (num+1)
        print "}"

it will generate java code which you can insert between these comments

//Insert explanation for lines of code below here.

and it will sort your five digits. Basically it does bubble sort with the both loops unrolled.

Don't waste your time manually entering sorting statements. Computers do exist to do the boring work for us!

if (digit1 < digit2) {
    System.out.println("Swapping "+digit1+" and "+digit2);
    int temp=digit1;
    digit1=digit2;
    digit2=temp;
}
if (digit2 < digit3) {
    System.out.println("Swapping "+digit2+" and "+digit3);
    int temp=digit2;
    digit2=digit3;
    digit3=temp;
}
...
    System.out.print("Enter a five digit integer number: ");

    int fiveInt, digit1, digit2, digit3, digit4, digit5; // Declaring
                                                            // variables

    Scanner keyboard = new Scanner(System.in);

    fiveInt = keyboard.nextInt(); // User input will be required

    System.out.println(" "); // Prints empty line

    // The following will be explained assuming number entered was 12345.
    // The (int) will change whatever result of the division taking place to
    // an integer.

    digit1 = (int) (fiveInt / 10000); // 12345 divided by 10000 = 1.2345
                                        // converted to 1 due to (int).
    digit2 = ((int) (fiveInt / 1000)) - (digit1 * 10); // 12345 divided by
                                                        // 1000 = 12.345 -
                                                        // (1 * 10) = 2.345
                                                        // converted 2 due
                                                        // to (int).
    digit3 = ((int) (fiveInt / 100)) - (digit1 * 100) - (digit2 * 10); // 12345
                                                                        // divided
                                                                        // by
                                                                        // 100
                                                                        // =
                                                                        // 123.45
                                                                        // -
                                                                        // (1*100)
                                                                        // -
                                                                        // (2*10)
                                                                        // =
                                                                        // 3.45
                                                                        // converted
                                                                        // to
                                                                        // 3
                                                                        // due
                                                                        // to
                                                                        // (int).
    digit4 = ((int) (fiveInt / 10)) - (digit1 * 1000) - (digit2 * 100)
            - (digit3 * 10); // 12345 divided by 10 = 1234.5 - (1*1000) -
                                // (2*100) - (3*10) = 4.5 converted to 4 due
                                // to (int).
    digit5 = fiveInt - (digit1 * 10000) - (digit2 * 1000) - (digit3 * 100)
            - (digit4 * 10); // 12345 - (1*10000) - (2*1000) - (3*100) -
                                // (4*10) = 5

    System.out
            .println("The digits in " + fiveInt + " are: " + digit1 + ", "
                    + digit2 + ", " + digit3 + ", " + digit4 + ", "
                    + digit5);

    System.out.println(" "); // Prints empty line

    // Insert explanation for lines of code below here.

    if (digit1 < digit2) {
        int a = digit1;
        digit1 = digit2;
        digit2 = a;
    }

    if (digit2 < digit3) {
        int b = digit2;
        digit2 = digit3;
        digit3 = b;
    }

    if (digit3 < digit4) {
        int c = digit3;
        digit3 = digit4;
        digit4 = c;
    }

    if (digit4 < digit5) {
        int d = digit4;
        digit4 = digit5;
        digit5 = d;
    }

    // 2nd Filtering

    if (digit1 < digit2) {
        int a = digit1;
        digit1 = digit2;
        digit2 = a;
    }

    if (digit2 < digit3) {
        int b = digit2;
        digit2 = digit3;
        digit3 = b;
    }

    if (digit3 < digit4) {
        int c = digit3;
        digit3 = digit4;
        digit4 = c;
    }
    // 3rd Filtering

    if (digit1 < digit2) {
        int a = digit1;
        digit1 = digit2;
        digit2 = a;
    }

    if (digit2 < digit3) {
        int b = digit2;
        digit2 = digit3;
        digit3 = b;
    }

    // last filtering
    if (digit1 < digit2) {
        int a = digit1;
        digit1 = digit2;
        digit2 = a;
    }

    // Insert explanation for lines of code above here.

    System.out.print("The largest number with these digits is: " + digit1
            + digit2 + digit3 + digit4 + digit5); // Displays the digits in
                                                    // their sorted mann

I've written an algorithm in Java that solves this problem in bubble sort model algorithm and without seperating digits in an array or variables .

In my opinion this is the cleanest solution and could be the fastest one (I would appreciate if someone could actually benchmark this algorithm).

I originally created this algorithm because i was suprised of how nobody tried to solve this problem this way but rather storing each digit in seperate variables which uses more memory and in my opinion is a bad programming and thinking style because it holds boundaries such as fixed length of param integer.

Fork it @ Github

public static int main(int n) {
    int l, r;
    final int size = (int)(Math.log10(n));
    for (int i = 0; i < size; i++) 
        for (int k = i; k < size; k++) {
            r = (int)(n/Math.pow(10,k)%10);
            l = (int)(n/Math.pow(10,k+1)%10);
            if(l < r)
                n += Math.pow(10,k)*(l-r) + Math.pow(10,k+1)*(r-l);
        }
    return n;
}

Here's what I came up with. The basic idea is to find the minimum number and then invalidate this digit. Unfortunately that means that the original digit data is lost but you can always restore it from the user input int :

int currentMin;

System.out.print("The largest number with these digits is: ");

while(true) {
  currentMin = Math.min(digit1, Math.min(digit2, Math.min(digit3, Math.min(digit4, digit5))));
  //Invalidate the min digit
  if (currentMin == digit1) digit1 = Integer.MAX_INT;
  if (currentMin == digit2) digit2 = Integer.MAX_INT;
  if (currentMin == digit3) digit3 = Integer.MAX_INT;
  if (currentMin == digit4) digit4 = Integer.MAX_INT;
  if (currentMin == digit5) digit5 = Integer.MAX_INT;
  if (currentMin == Integer.MAX_INT) {
    break;
  } else {
    System.out.print(currentMin + " ");
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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