Learn how to a build a cloud-first strategyRegister Now

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

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
ADFB
Asked:
ADFB
  • 3
  • 2
1 Solution
 
gplanaCommented:
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
 
ADFBAuthor Commented:
I do that already, I thought using a quicksort would be faster.
0
 
gplanaCommented:
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
 
ADFBAuthor Commented:
Ah OK. If this is faster than that's better. Thanks.
0
 
gplanaCommented:
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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

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