Jyotirmay
Jyotirmay

Reputation: 554

Is there any way to sort the digits of an Integer without any ARRAY in JAVA?

I am trying to sort the digits of an Integer in descending order in JAVA but I am not allowed to use any array.

This was given to me as an assignment in class and below is a code that I tried but failed.

import java.util.Scanner;
class descend
{
    public static void main(String args[])
    {
        int a=0,loc=0,parse=0,temp=0,big=0;
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter a number");
        a=scan.nextInt();
        String s=Integer.toString(a);
        int l=s.length();
        for(int i=0;i<l;i++)
        {
            big=(int)(s.charAt(i));
            loc=i;
            for(int j=i+1;j<l;j++)
            {
                parse=(int)(s.charAt(j));
                if(parse>big)
                {
                    big = parse;
                    loc=j;
                }
            }
            temp=parse;
            s.charAt(i)=s.charAt(loc);
            s.charAt(loc)=temp
        }
        System.out.print(s);
    }
}

Here I get a syntax error at s.charAt(i)=s.charAt(loc); and s.charAt(loc)=temp; that a variable is required but a value is given.

Please help me out with this and I shall always be grateful to you.

Upvotes: 0

Views: 133

Answers (4)

Jyotirmay
Jyotirmay

Reputation: 554

Sorry, But after applying so much effort, I figured it out.

int n=54321;char ch;
String s=Integer.toString(n);
int l= s.length();
for(int i=48;i<=57;i++)    //ascii values from 0 - 9
{
    for(int j=0;j<l;j++)
    {
      ch=s.charAt(j);
      if(ch==(char)i)    // checking if a digit equals a number
      {
        System.out.print(ch);
      }
    }
}

It sorts the digits in ascending order. To sort in descending order we should use

for(int i=57;i>=48;i--)

Upvotes: 0

Chaarmann
Chaarmann

Reputation: 154

Maybe the teacher want to test your knowledge about the new stream API. Or maybe he wants you to test your knowledge about Collections.sort() and LinkedList (which does not contain an internal array).

1.) Here is a solution with stream API:

int number = 52214;
String.valueOf(number).chars()
   .sorted()
   .map(Character::getNumericValue).forEach(System.out::print);

This will print out:

12245

2.) Here is a solution with collections:

List<Integer> list = new LinkedList<Integer>();
StringCharacterIterator iterator = new StringCharacterIterator(String.valueOf(number));
for (char c = iterator.first(); c != CharacterIterator.DONE; c = iterator.next()) 
{
    list.add(Character.getNumericValue(c));
}
Collections.sort(list);
System.out.println("list=" + list);

This will print out:

list=[1, 2, 2, 4, 5]

Upvotes: 1

Bentaye
Bentaye

Reputation: 9756

A recursive solution, you find the highest digit in the String, add it to your output String, and remove it from your input String. Repeat until your input String is empty.

Removing the character at a given index in a String can be achieve by concatenating the characters before the index and the ones after the index. (Or with a StringBuilder but I agree with the comments on the OP that it would be cheating to use a StringBuilder)

private static String sort(String digitsLeftToSort, String sortedString) {
    if(digitsLeftToSort.length() == 0) { // no more character to sort
        return sortedString;
    } else {
        // find the index of the highest digit
        int index = findIndexOfHighestDigit(digitsLeftToSort);
        // add the character at that index to your output String
        sortedString += digitsLeftToSort.charAt(index);
        // Remove it from your input String
        digitsLeftToSort = digitsLeftToSort.substring(0, index) + digitsLeftToSort.substring(index+1);
        // Recursive call with your new Strings
        return sort(digitsLeftToSort, sortedString);
    }
}

// This finds the index of the highest digit in the given String
private static int findIndexOfHighestDigit(String s) {
    int highestDigitValue = -1;
    int highestDigitIndex = -1;
    int integerValue;
    for(int i = 0; i< s.length(); i++) {
        integerValue = Character.getNumericValue(s.charAt(i));
        if(integerValue > highestDigitValue) {
            highestDigitValue = integerValue;
            highestDigitIndex = i;
        }
    }

    return highestDigitIndex;
}

Then

String sortedString = sort("462375623478142", "");
System.out.println(sortedString);

Outputs

877665444332221

Upvotes: 0

Joop Eggen
Joop Eggen

Reputation: 109547

String cannot be changed, only replaced, hence a = b; f(b); will never change a.

With 10 digits only, you could iterate, step through, from 0 upto 9 to have the sorting:

int number = ... // or String number
if (number == 0) { // or < 10
    System.out.println(number);
} else {
    for (int digit = 0; digit <= 9; ++digit) {
        // While being able to remove the current digit:
        for (;;) {
            int scrapedNumber = numberWithoutDigitOnce(number, digit);
            if (scrapedNumber == number) {
                break;
            }
            number = scrapedNumber;
            System.out.print(digit);
        }
    }
    System.out.println();
}

int numberWithoutDigitOnce(int number, int digit) {
    if (number % 10 == digit) {
        return number / 10;
    }
    int n = numberWithoutDigitOnce(number/10, digit)*10 + (number % 10);
}

Zero is a special case.

Upvotes: 0

Related Questions