Sort numeric digits without using an array

What I need to do for my homework is to sort the numbers of a positive number from low to high.

I can use

  • Operators
  • integers / doubles / floats / characters
  • if / switch and loop

I can not use

  • char array ()
  • line
-3
sorting arrays
source share
4 answers

It will do it!

int number = 52146729; int sortedNumber = 0; for (int i = 9; i >= 0; i--) { int tmpNumber = number; while (tmpNumber > 0) { int digit = tmpNumber % 10; if (digit == i) { sortedNumber *= 10; sortedNumber += digit; } tmpNumber /= 10; } } System.out.println(sortedNumber); 

This is java btw. Given the limitations, this is pretty effective, O (n).

+15
source share

Given the complete lack of requirements, I'm not sure if this will help, but I would use the LINQ OrderBy list and method if I did this in production code:

 List<int> testList = new List<int> { 1, 5, 10, 4, 2 }; IEnumerable<int> orderedList = testList.OrderByDescending(x => x); 

To sort numbers, you must clearly understand what an "array" is. For this you need some kind of collection. I would use the list again:

 List<int> digits = new List<int>(); int remainingNumber = 52146729; while (remainingNumber > 0) { digits.Add(remainingNumber % 10); remainingNumber /= 10; } IEnumerable<int> orderedDigits = testList.OrderByDescending(x => x); 

This works because x mod y returns the remainder of x / y. So 9% 10 returns nine, so 19% 10, etc. Then you divide by 10 to get rid of one digit, and repeat until you finish. Then I use the same order function as before. This approach definitely does not use strings or any explicit arrays (List is an array under the hood). As I said, doing this without any collection will be really ugly.

The listing of this list will be simple (if you just need to print it for output):

 foreach (int i in orderedDigits) Console.Write(i); 

If you need a real number, it will be a little more complicated, so I will leave it now.

0
source share

Why aren't you trying to use a tree?

Create a tree with two children: left and right. The rest of the children store lower numbers, and the right children store higher numbers. So you need to consider Node having two possible options. The first number will be the root of the tree. The next number can be saved left or right.

After the tree is filled, you can access each number using the approach in the following order: 1- Read left; 2- Read the parent; 3- Read the settings.

Check it out: http://en.wikipedia.org/wiki/Tree_traversal

0
source share

Make a numbering style:

 int count9 int count8 int count7 int count6 int count5 int count4 int count3 int count2 int count1 int count0 // loop over the number and fill in the counts. (either with characters or by using %10) for (int i = 0; i < count9; i++) print "9" // more for loops, etc, downto 8. 

Definitely not production code, but this is largely ruled out by destination restrictions.

Hope this helps!

0
source share

All Articles