note 30998 deleted from function.sort by derick

From: Date: Wed, 31 Aug 2005 10:40:05 +0000
Subject: note 30998 deleted from function.sort by derick
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-94505@lists.php.net to get a copy of this message
Note Submitter: ---- Written by George Andre P. Here is Insertion Sort, that preserves the keys of the array while it sorts the values. Works for 1D array whose keys are positive integers I think :) function insertionSort($str_) { foreach ($str_ as $key => $val) { $val_[] = $val; $key_[] = $key; } for ($i = 1; $i < count ($val_); $i++) { $index = $val_[$i]; $kindex = $key_[$i]; $j = $i; while (($j > 0) && ($val_[$j - 1] > $index)) { $val_[$j] = $val_[$j - 1]; $key_[$j] = $key_[$j - 1]; $j = $j - 1; } $val_[$j] = $index; $key_[$j] = $kindex; } foreach ($val_ as $key => $val) { $new_[$key_[$key]] = $val; } return $new_; } Here is test to prove the functionality of the sort: // Test insertionSort. if (isSet ($sorted_)) { foreach ($sorted_ as $key => $val) { echo $key . ' => ' . $val . '<br>'; } } Enjoy. Hope that helps some one. Remember: Knowledge Bellongs To The Universe. Share it! I know I probably have said this a million times, but PHP Developers thanks for PHP again!

« previous php.notes (#94505) next »