Array Sorting
Jarrett Billingsley
kb3ctd2 at yahoo.com
Wed Jun 20 05:46:35 PDT 2007
"okibi" <okibi at ratedo.com> wrote in message
news:f5b5a1$187u$1 at digitalmars.com...
> Hey,
>
> I was wondering if there is a way to sort three digit numbers.
>
> Doing an array.sort will result in a sequence such as this:
>
> 1
> 10
> 2
> 24
>
> What I want is it to get sorted like this:
>
> 1
> 2
> 10
> 24
>
> Is there an easy way to specify this? Putting a 0 in front is not an
> option.
>
> Thanks!
I take it you have an array of strings.
Unfortunately the array .sort property does not allow you to use a custom
sorting predicate, and phobos doesn't provide any predicate-using sort
function like Tango does. You can get by pretty well by using a struct
array:
struct NumString
{
char[] data;
int opCmp(NumString* other)
{
int myNum = toInt(data);
int otherNum = toInt(other.data);
return myNum - otherNum;
}
}
...
NumString[] arr = new NumString[10];
// fill it
arr.sort;
// tada
Or, you can write a function that will take an array and a sorting
predicate, and do the sort yourself. Or, you can use the C stdlib qsort
(but that's not pretty at all). Or use Tango. Or use Cashew. :)
More information about the Digitalmars-d-learn
mailing list