note 30998 added to function.sort

From: Date: Sun, 06 Apr 2003 01:24:46 +0000
Subject: note 30998 added to function.sort
Groups: php.notes 
Request: Send a blank email to php-notes+get-46270@lists.php.net to get a copy of this message
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! -- http://www.php.net/manual/en/function.sort.php http://master.php.net/manage/user-notes.php?action=edit+30998 http://master.php.net/manage/user-notes.php?action=delete+30998 http://master.php.net/manage/user-notes.php?action=reject+30998

« previous php.notes (#46270) next »