fork download
  1. <?php
  2. function quicksort( $array )
  3. {
  4. $cur = 1;
  5. $stack[1]['l'] = 0;
  6. $stack[1]['r'] = count($array)-1;
  7.  
  8. do
  9. {
  10. $l = $stack[$cur]['l'];
  11. $r = $stack[$cur]['r'];
  12. $cur--;
  13.  
  14. do
  15. {
  16. $i = $l;
  17. $j = $r;
  18. $tmp = $array[(int)( ($l+$r)/2 )][1];
  19.  
  20. // partion the array in two parts.
  21. // left from $tmp are with smaller values,
  22. // right from $tmp are with bigger ones
  23. do
  24. {
  25. while( $array[$i][1] < $tmp )
  26. $i++;
  27.  
  28. while( $tmp < $array[$j][1] )
  29. $j--;
  30.  
  31. // swap elements from the two sides
  32. if( $i <= $j )
  33. {
  34. $w = $array[$i];
  35. $array[$i] = $array[$j];
  36. $array[$j] = $w;
  37.  
  38. $i++;
  39. $j--;
  40. }
  41.  
  42. }while( $i <= $j );
  43.  
  44.  
  45. if( $i < $r )
  46. {
  47. $cur++;
  48. $stack[$cur]['l'] = $i;
  49. $stack[$cur]['r'] = $r;
  50. }
  51. $r = $j;
  52.  
  53. }while( $l < $r );
  54.  
  55. }while( $cur != 0 );
  56.  
  57. return $array;
  58. }
  59.  
  60. function microtime_float()
  61. {
  62. list($usec, $sec) = explode(" ", microtime());
  63. return ((float)$usec + (float)$sec);
  64. }
  65.  
  66. function set(&$uzytkownik)
  67. {
  68. $uzytkownik[0][0] = "Jasiu";
  69. $uzytkownik[0][1] = 22;
  70. $uzytkownik[1][0] = "Wacek";
  71. $uzytkownik[1][1] = 21;
  72. $uzytkownik[2][0] = "Misiek";
  73. $uzytkownik[2][1] = 16;
  74. $uzytkownik[3][0] = "Kasia";
  75. $uzytkownik[3][1] = 11;
  76. }
  77.  
  78. function cmpfunc($a, $b){return ($a[1] == $b[1]) ? 0 : ($a[1] < $b[1]) ? -1 : 1;}
  79.  
  80. $time = microtime_float();
  81. for ($i = 0; $i<5000; $i++)
  82. {
  83. set($uzytkownik);
  84. usort($uzytkownik, 'cmpfunc');
  85. }
  86. $time = microtime_float()-$time;
  87. echo "usort: ".$time."<br>";
  88.  
  89. $time = microtime_float();
  90. for ($i = 0; $i<5000; $i++)
  91. {
  92. set($uzytkownik);
  93. $uzytkownik = quicksort($uzytkownik);
  94. }
  95. $time = microtime_float()-$time;
  96. echo "quicksort: ".$time."<br>";
  97. ?>
Success #stdin #stdout 0.11s 13112KB
stdin
Standard input is empty
stdout
usort: 0.0313699245453<br>quicksort: 0.0621209144592<br>