473,788 Members | 2,784 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sort a number highest to lowest

Hi,

I'm trying to create a function that will sort a number's digits
from highest to lowest.

For example

1000 - will become 0001

or 1234 to 4321

Is it better to covert the number to a string first then sort? or
is there a better way to do it?
I just need some clues on how to do it. I've tried to search some
materials on how to do it but I only saw how to sort a 'LIST' but not
just a number.
Thanks for the help

Dec 10 '06 #1
17 7720
rh*******@gmail .com wrote:
Hi,

I'm trying to create a function that will sort a number's digits
from highest to lowest.

For example

1000 - will become 0001

or 1234 to 4321

Is it better to covert the number to a string first then sort? or
is there a better way to do it?
Think again about what you are attempting to sort - the decimal
representation of a binary number. So you aren't sorting the number,
but a textual representation of it. The textual representation is a .....
I just need some clues on how to do it. I've tried to search some
materials on how to do it but I only saw how to sort a 'LIST' but not
just a number.
If you consider what you are sorting, you will see the list.

--
Ian Collins.
Dec 10 '06 #2
rh*******@gmail .com said:
Hi,

I'm trying to create a function that will sort a number's digits
from highest to lowest.

For example

1000 - will become 0001

or 1234 to 4321

Is it better to covert the number to a string first then sort? or
is there a better way to do it?
Buckets, my dear chap! Buckets! The world's fastest sorting technique this
side of Lucksort!
I just need some clues on how to do it. I've tried to search some
materials on how to do it but I only saw how to sort a 'LIST' but not
just a number.
Presuming you are dealing only with digits in base N, you can define an
array of N digits, and clear it down to all 0s. If N is a constant integer
expression (or if you are using C99) you can do this:

unsigned long digit[N] = {0};

Now iterate through the number, modding with N. Let's first deal with the
silly case:

if(n == 0)
{
++digit[0];
}
else
{
/* and now we count digits */
while(digit 0)
{
++digit[n % N];
digit /= N;
}
}

You now have your digit count, and it remains only to iterate through your
array, printing out the digits in whichever order it seems best to you,
making sure you print each the appropriate number of times.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Dec 10 '06 #3
<rh*******@gmai l.comwrote in message
news:11******** **************@ 80g2000cwy.goog legroups.com...
Hi,

I'm trying to create a function that will sort a number's digits
from highest to lowest.

For example

1000 - will become 0001
You mean 1000 will stay 1000?
or 1234 to 4321

Is it better to covert the number to a string first then sort? or
is there a better way to do it?
I just need some clues on how to do it. I've tried to search some
materials on how to do it but I only saw how to sort a 'LIST' but not
just a number.
Thanks for the help
There is a number of solutions. If you don't like to sort too much, and your
number is an integer, you could always do the following: If your number is in
base N, then make an array of integers which is N elements long (and initially
all elements are 0).

Now take your number and do a mod N on it. The result is the last digit of that
number. Let's say the digit is X. Increase the X-th element of your array by 1.
Now divide the original number by N. Since your number and N are both integers,
what you will do is remove the last digit. Now do the same for the other digits
in a loop, until what is left of your number is 0.

Now you will have an array with its elements telling you how many of each digit
there is. Define Y as integer and set it to 1. Iterate through the array. If the
current element is 0, decrease it by 1 and do:

result += X * Y;
Y *= N;

Where X is the current element of the array (not its value, but its position in
that array). I assume 'result' is equal to 0 before this. Do this until the X-th
element is = 0.
When these two loops are done, variable 'result' will contain your result.

--
"It is easy in the world to live after the world's oppinion; it easy in solitude
to live after our own; but the great man is he who in the midst of the crowd
keeps with perfect sweetness the independence of solitude."
Ralph Waldo Emerson, Self-reliance 1841
http://pinpoint.wordpress.com/

Dec 10 '06 #4
Sourcerer said:

<duplicate of my solution snipped>

Now you will have an array with its elements telling you how many of each
digit there is. Define Y as integer and set it to 1. Iterate through the
array. If the current element is 0, decrease it by 1 and do:

result += X * Y;
Y *= N;
You don't need to do this, and indeed it is fraught with peril. Consider,
for example, 16-bit ints and an input of 12789. The required output is
98721, but that won't fit in a 16-bit int. (For 32-bit ints, the same
problem exists - just pick a bigger example.)

There is no need to calculate. You can simply iterate through the array,
printing the appropriate number of digits in each bucket as you go.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Dec 10 '06 #5
>
There is no need to calculate. You can simply iterate through the array,
printing the appropriate number of digits in each bucket as you go.


Thanks. I was able to print the numbers in the array and was able to
sort them in ascending and descending order. Now I would like to print
these integers as one int variable, so I was thinking of concatenating
the integers (like a string) then convert them to integer (atoi)..

But I'm not really quite sure how I can concatenate these array of
integers, Any ideas?
how about the sprintf?

Thanks again for the help.

Dec 10 '06 #6
"Richard Heathfield" <rj*@see.sig.in validwrote in message
news:b4******** *************** *******@bt.com. ..
Sourcerer said:

<duplicate of my solution snipped>
Sorry about that, I didn't read it.
>Now you will have an array with its elements telling you how many of each
digit there is. Define Y as integer and set it to 1. Iterate through the
array. If the current element is 0, decrease it by 1 and do:

result += X * Y;
Y *= N;

You don't need to do this, and indeed it is fraught with peril. Consider,
for example, 16-bit ints and an input of 12789. The required output is
98721, but that won't fit in a 16-bit int. (For 32-bit ints, the same
problem exists - just pick a bigger example.)

There is no need to calculate. You can simply iterate through the array,
printing the appropriate number of digits in each bucket as you go.
True. It wouldn't be perilous, I believe it will just give an incorrect result.
I was thinking that an integer must hold the answer, but now I see this isn't
specified, it only says to sort. You can always define your own type, though,
and functions to deal with them.

--
"It is easy in the world to live after the world's oppinion; it easy in solitude
to live after our own; but the great man is he who in the midst of the crowd
keeps with perfect sweetness the independence of solitude."
Ralph Waldo Emerson, Self-reliance 1841
http://pinpoint.wordpress.com/

Dec 10 '06 #7
rh*******@gmail .com wrote:
There is no need to calculate. You can simply iterate through the array,
printing the appropriate number of digits in each bucket as you go.
<snip>
Thanks. I was able to print the numbers in the array and was able to
sort them in ascending and descending order. Now I would like to print
these integers as one int variable, so I was thinking of concatenating
the integers (like a string) then convert them to integer (atoi)..

But I'm not really quite sure how I can concatenate these array of
integers, Any ideas?
how about the sprintf?
Please provide attributions.

It's not clear what you want to do. Do you want to print the sum of all
the integers in the array? If so, that ought to be obvious.

On the other hand, do you want to print the integers as big string, one
after the other. If so, you can do:

for(counter = 0; counter < elements_in_arr ay; counter++) printf("%d",
array[counter]);
fflush(stdout);

Dec 10 '06 #8
<rh*******@gmai l.comwrote in message
news:11******** **************@ 73g2000cwn.goog legroups.com...
>
Thanks. I was able to print the numbers in the array and was able to
sort them in ascending and descending order. Now I would like to print
these integers as one int variable, so I was thinking of concatenating
the integers (like a string) then convert them to integer (atoi)..

But I'm not really quite sure how I can concatenate these array of
integers, Any ideas?
how about the sprintf?

Thanks again for the help.
So, the result must be an int variable, or do you just want to print it out?
As already pointed out by Richard, you can't do the primer safely, because of
the possible overflow.
The latter, you can do by making the array of characters instead of an array of
integers, and make sure that you are adding '0' to each value you are entering
into an array. Be careful if N (base) is larger than 10, because then you need
to add '0' to digits 0-9, and 'A' for the rest (I assume you won't be going
higher than base 16 - although this would support base 36). After this is done,
you can print it out as string (but don't forget about the delimiter!).
If this is not satisfactory, there are other, but significantly more complicated
solutions.

--
"It is easy in the world to live after the world's oppinion; it easy in solitude
to live after our own; but the great man is he who in the midst of the crowd
keeps with perfect sweetness the independence of solitude."
Ralph Waldo Emerson, Self-reliance 1841
http://pinpoint.wordpress.com/

Dec 10 '06 #9
rh*******@gmail .com skrev:
I'm trying to create a function that will sort a number's digits
from highest to lowest.

For example

1000 - will become 0001

or 1234 to 4321

Is it better to covert the number to a string first then sort? or
is there a better way to do it?
I just need some clues on how to do it. I've tried to search some
materials on how to do it but I only saw how to sort a 'LIST' but not
just a number.
Thanks for the help
Here's one way to do it:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int cmp(const void *p, const void *q)
{
char a = *((char *) p), b = *((char *) q);

if (a < b) { return -1; }
else if (a == b) { return 0; }
else { return 1; }
}
int main(int argc, char **argv)
{
int len; char *buf;

if (argc != 2) {
fprintf(stderr, "Error: one integer parameter required");
exit(EXIT_FAILU RE);
}
len = strlen(argv[1]);
buf = malloc(len + 1);
strcpy(buf, argv[1]);
qsort(buf, len, 1, cmp);
printf("%s\n", buf);
return 0;
}
August
Dec 10 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3253
by: nick_faye | last post by:
hi guys, im still a newbie in ms-access and i would like to ask how can i get the highest and the lowest date in ms-access report? for example, i have these entries: 10/1/2003 10/5/2003 10/2/2003 10/4/2003 10/2/2003 10/3/2003
21
13484
by: Jaspreet | last post by:
I was working on some database application and had this small task of getting the second highes marks in a class. I was able to do that using subqueries. Just thinking what is a good way of getting second highest value in an integer array. One method I know of is to make the 1st pass through the array and find the highest number. In the second pass we can find the highest number which is less than the number we obtained in the 1st pass.
5
5454
by: owz | last post by:
Hi again had some more problems, all help welcome. Access 2000, SQL My problem is as stated in the title. I want 2 display the highest and lowest priced car sold for this month. This is what I have. SELECT CarSales.Car_Reg,MAX (Purchased_Price) AS Highest_Sale FROM CarSales WHERE Purchased_Price=(SELECT MIN(Purchased_Price)AS Smallest_Sale FROM...
1
5875
by: coolindienc | last post by:
I got this program running and gives me result that I want (actually not yet). Now I want to find out the lowest and highest numbers I entered. Andy advise??? number = int (input ("Enter a positive number that is below 126: ")) if number > 125: print "The number entered has to be 125 or lower.\n" number = input ("Enter a positive number that is below 126: ") else: total = 0 total += number
3
6577
by: laredotornado | last post by:
Hi, I have ten DIVs on my page, with IDs "e1" ... "e10". These DIVs can get moved around on the screen in the course of the page interaction. However, at a certain point, I would like to be able to sort where the DIVs are currently positioned, using the top left coordinate as the reference point, sorting from lowest "x" position to highest, and in the case of a tie, sorting from lowest "y" position to highest. Any ideas on an...
13
141303
by: td0g03 | last post by:
Hello again guys. I have a question. I'm working on a program for my class and I'm stuck on how to find the lowest and highest number of a user input. We aren't at arrays yet so that's out of the question, but what would be another way of finding the highest and lowest. I remember hearing something in the lines of "cout <<" in class, but forgot. Also I could try the if else statement, but would seem like alot of work. I hope I am making this...
6
29329
by: fenners87 | last post by:
Hi I need to write a programme that asks users to enter 10 numbers and once the numbers have been entered i then need to sort them from lowest to highest in C# i.e 45, 3, 64, 6, 24, 75 3, 6, 24, 45, 64, 75 I am unsure on how to do it and what to use? So far i have used strings to store the numbers entered,
4
2323
by: cnixuser | last post by:
Hello, I am attempting to create a prime number detector that will identify all of the prime numbers within a specified range of numbers. The problem is, for some reason my program is not detecting any prime numbers and seems to be only to be printing one value of zero from the array that I am trying to store the prime numbers detected in. I believe the zero is coming from the value already stored in the array when I initialzed it, which means...
16
539
by: jason.cipriani | last post by:
I am looking for a random number generator implementation with the following requirements: - Thread-safe, re-entrant. - Produces consistently reproducible sequences of psuedo-random numbers given a seed. - Relatively uniform, does not have to be perfect. The application is not a security or statistics application, the quality of numbers is not a priority although a fairly uniform
0
9656
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9498
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9969
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8995
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7519
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5538
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4074
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3677
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2897
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.