Learn how to a build a cloud-first strategyRegister Now

x
• Status: Solved
• Priority: Medium
• Security: Public
• Views: 245

# Sorting Array by Another

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
• 3
• 2
1 Solution

Commented:
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 Commented:
I do that already, I thought using a quicksort would be faster.
0

Commented:
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 Commented:
Ah OK. If this is faster than that's better. Thanks.
0

Commented:
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

• 3
• 2
Tackle projects and never again get stuck behind a technical roadblock.