Search code examples
javaalgorithmbubble-sort

how can I sorting a number without using array?


How can I find the maximum and the minimum number that can be formed using digits of a given number (for example 485735) without using any array at all ?

I was looking at the algorithm of bubble sort (that using array) and I tried to figure out how to write an algorithm without the array but my problem was to counting the indexes of every digit

The only thing that cross my mind was an algorithm to count the number of digits in the input (friend helped me with that) , but so far I'm tried to figure this thing out for a 4 days that's a question with a grade from my homework

the rule is that the smallest number can't start in a zero for example:

Input: 3134059 
The largest number is: 9543310
The smallest number is: 1033459

Solution

  • public static void main(String[] args) {
    
        StringBuilder s = new StringBuilder("4857035");
        char aux;
    
        for (int i = 0; i < s.length() - 1; i++) {
            for (int j = i + 1; j < s.length(); j++) {
                if (s.charAt(i) > (s.charAt(j))) {
                    aux = s.charAt(i);
                    s.setCharAt(i, s.charAt(j));
                    s.setCharAt(j, aux);
                }
            }
        }
        //output 0345578
    
        while (s.charAt(0) == '0') {
            for (int i = 1; i < s.length(); i++) {
                if (s.charAt(i) != '0') {
                    aux = s.charAt(0);
                    s.setCharAt(0, s.charAt(i));
                    s.setCharAt(i, aux);
                    break;
                }
            }
        }
        //output 3045578
    }
    

    This is for the smallest number, for the greatest number change the sign on if statement ( if (s.charAt(i) < (s.charAt(j))) and delete the while statement.