473,395 Members | 1,738 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

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 7643
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*******@gmail.comwrote in message
news:11**********************@80g2000cwy.googlegro ups.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.invalidwrote 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_array; counter++) printf("%d",
array[counter]);
fflush(stdout);

Dec 10 '06 #8
<rh*******@gmail.comwrote in message
news:11**********************@73g2000cwn.googlegro ups.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_FAILURE);
}
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

Sourcerer wrote:
>
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.

My apologies for not making my question clear. Basically what I really
wanted to accomplish is for a 4-digit number for ex:

1342

I would like to sort it from highest to lowest, then from lowest to
highest, therefore that will give me

4321
1234

then I would need to subtract the lower number from the higher number..

So far I was able to arrange the numbers from highest to lowest and
vice versa but I used integer array.. So I have:

(sorted array)
array[0] = 1
array[1] = 2
array[2] = 3
array[3] = 4

I wonder if i can just compare the two integer arrays, then subtract
the lower int array from the higher int array..

I'll try that and see if will work..

Appreciate if somebody will give me some clues too..

Thanks...

Dec 10 '06 #11
rhitz1...@gmail.com wrote:
Sourcerer wrote:
So, the result must be an int variable, or do you just want to print it out?
<snip>
My apologies for not making my question clear. Basically what I really
wanted to accomplish is for a 4-digit number for ex:

1342

I would like to sort it from highest to lowest, then from lowest to
highest, therefore that will give me

4321
1234

then I would need to subtract the lower number from the higher number..

So far I was able to arrange the numbers from highest to lowest and
vice versa but I used integer array.. So I have:

(sorted array)
array[0] = 1
array[1] = 2
array[2] = 3
array[3] = 4
The easiest thing to do is to convert each array to an integer value
and subtract the lower from the higher. For example:

long high2low = strtol(array_descending, NULL, 0);
long low2high = strtol(array_ascending, NULL, 0);
long diff = high2low - low2high;
printf("%ld\n", diff);

Here array_descending and array_ascending are your two arrays, containg
the number in it's two sorted forms, as a sequence of characters.
strtol() converts them to a long value. Note that in your actual code,
you'll want to check strtol() for failure.

Dec 10 '06 #12
August Karlstrom said:

<snip>
int cmp(const void *p, const void *q)
{
char a = *((char *) p), b = *((char *) q);
Discarding const...
int main(int argc, char **argv)
{
int len; char *buf;

if (argc != 2) {
fprintf(stderr, "Error: one integer parameter required");
exit(EXIT_FAILURE);
}
len = strlen(argv[1]);
....signed/unsigned mismatch...
buf = malloc(len + 1);
strcpy(buf, argv[1]);
....and failing to check malloc's return value before relying on it for
memory. Oopsie.

--
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 #13
Richard Heathfield <rj*@see.sig.invalidwrites:
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)
n>0
{
++digit[n % N];
digit /= N;
n/=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.

Dec 10 '06 #14
Richard Heathfield skrev:
August Karlstrom said:

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

Discarding const...
>int main(int argc, char **argv)
{
int len; char *buf;

if (argc != 2) {
fprintf(stderr, "Error: one integer parameter required");
exit(EXIT_FAILURE);
}
len = strlen(argv[1]);

...signed/unsigned mismatch...
> buf = malloc(len + 1);
strcpy(buf, argv[1]);

...and failing to check malloc's return value before relying on it for
memory. Oopsie.
OK, thanks for the remarks.

And here is the corrected version:

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

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

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

if (argc != 2) {
fprintf(stderr, "Error: one parameter required");
exit(EXIT_FAILURE);
}
len = strlen(argv[1]);
buf = malloc(len + 1);
if (!buf) {
fprintf(stderr, "Error: malloc failed");
exit(EXIT_FAILURE);
}
strcpy(buf, argv[1]);
qsort(buf, len, 1, cmp);
printf("%s\n", buf);
free(buf);
return 0;
}
August
Dec 10 '06 #15
Richard said:
Richard Heathfield <rj*@see.sig.invalidwrites:
> /* and now we count digits */
while(digit 0)

n>0
Ouch!
>
> {
++digit[n % N];
digit /= N;

n/=N;
Ouch^2!

Thanks. Er, twice.

When did I write that? As in, what time of day?

<checks>

Bleargh!

--
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 #16
>
The easiest thing to do is to convert each array to an integer value
and subtract the lower from the higher. For example:

long high2low = strtol(array_descending, NULL, 0);
long low2high = strtol(array_ascending, NULL, 0);
long diff = high2low - low2high;
printf("%ld\n", diff);

Here array_descending and array_ascending are your two arrays, containg
the number in it's two sorted forms, as a sequence of characters.
strtol() converts them to a long value. Note that in your actual code,
you'll want to check strtol() for failure.
but my array_descending and array_ascending are both ints, to use the
strtol, isn't they have to be strings? plus in my output, i want it to
be an integer too, because I will have to perform another operation for
it:

FYI:
I'm trying to create a program that will find a fixed point of a
number, for example:
the number 321:

So the process will be:
321 - 123 = 198
198 - 189 = 792
963 - 369 = 594
954 - 459 = 495
954 - 459 = 495 ===fixed point..

i was able to have to do desc and asc part, now just a matter of doing
the subraction, getting the answer..
thanks a lot

Dec 10 '06 #17
rh*******@gmail.com wrote:

The easiest thing to do is to convert each array to an integer value
and subtract the lower from the higher. For example:

long high2low = strtol(array_descending, NULL, 0);
long low2high = strtol(array_ascending, NULL, 0);
long diff = high2low - low2high;
printf("%ld\n", diff);

Here array_descending and array_ascending are your two arrays, containg
the number in it's two sorted forms, as a sequence of characters.
strtol() converts them to a long value. Note that in your actual code,
you'll want to check strtol() for failure.

but my array_descending and array_ascending are both ints, to use the
strtol, isn't they have to be strings? plus in my output, i want it to
be an integer too, because I will have to perform another operation for
it:
Well, you need to convert the integer array into an integer. Do
something like:

int value = 0, counter, digit_pos = 0;

/* Find the last meaningful element of the array. For example if your
array has five elements and holds the values arr[0] == 4, arr[1] == 3,
arr[2] == 2, arr[3] == 1, arr[4] == garbage_value, then the last
meaning full element is 3. */

for(counter = last_meaningful_element; counter >= 0; counter++,
digit_pos++)
value += array[counter] * pow(10, digit_pos);

After the loop is complete, value holds the integer value represented
by the array elements. Do the same for both arrays and then perform
your subtraction.

Dec 11 '06 #18

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

Similar topics

2
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...
21
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...
5
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...
1
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...
3
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...
13
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...
6
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 ...
4
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...
16
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.