Link to home
Start Free TrialLog in
Avatar of ADFB
ADFB

asked on

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!
ASKER CERTIFIED SOLUTION
Avatar of gplana
gplana
Flag of Spain image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ADFB
ADFB

ASKER

I do that already, I thought using a quicksort would be faster.
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
Avatar of ADFB

ASKER

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