Solved

# Sorting Array by Another

Posted on 2011-10-08
244 Views
I know this has been asked many times but I don't understand the answers...

Basically I have two arrays.

The first is \$wordlist and contains a list of words. (e.g. \$wordlist[0]='hello'; \$wordlist[1]='bye';)

The second is \$weight and contains a list of numbers where each value is the weight of the corresponding word from \$wordlist with the same array number. (e.g. \$weight[0]=100; \$weight[1]=150;)

So I just want to sort the \$wordlist array by the \$weight array so that the highest weight is first. Actually I only want to find the highest weight, it's not totally necessary to return the full list.

I could just loop through the array to find the highest, but I don't want to do this because \$wordlist is very long and the function is called a lot, so that would slow down the script. Better to use a quicksort implementation (such as the PHP built-in sorts).

How would I do this?

Thanks!
0

LVL 15

Accepted Solution

You should do something like this:

\$maxweight = 0;
\$n = \$weight.length;
for (\$i=0; \$i<\$n; \$i++) {
\$w = \$weight[\$i];
if (\$maxweight<\$w) {
\$word = \$wordlist[\$i];
}
}
echo \$word;
0

Author Comment

I do that already, I thought using a quicksort would be faster.
0

LVL 15

Expert Comment

But you say you need only the word with maximum weight, not the entire ordered list.

A quick sort is better for ordering the entire list, but not for finding a single element. This is best way (just a single loop to check the weight of every element).

Regards
0

Author Comment

Ah OK. If this is faster than that's better. Thanks.
0

LVL 15

Expert Comment

Yes, to find a maximum costs O(n), while to order an array by using quicksort costs about O(n*log n).

So if you have a thousand elements this will lmake a thousand comparations, while quicksort will do about a ten thousand comparations in average.

Regards.
0

## Featured Post

Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.