Created
February 21, 2019 18:11
-
-
Save flolanger/73f1ef0fe76878738c272ef5ddab3f17 to your computer and use it in GitHub Desktop.
QuickSort algorithm in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class sort | |
{ | |
public function quicksort(array $data, $left, $right) | |
{ | |
if ($left < $right) { | |
$splitpos = $this->split($data, $left, $right); | |
$data = $this->quicksort($data, $left, $splitpos -1); | |
$data = $this->quicksort($data, $splitpos +1, $right); | |
} | |
return $data; | |
} | |
public function split(array &$data, $left, $right) | |
{ | |
$pivot = $right; | |
$pivotValue = $data[$pivot]; | |
do { | |
while ($data[$left] < $pivotValue && $left < $right){ | |
$left++; | |
} | |
while ($data[$right] >= $pivotValue && $left < $right){ | |
$right--; | |
} | |
$temp = $data[$left]; | |
$data[$left] = $data[$right]; | |
$data[$right] = $temp; | |
} | |
while($left < $right); | |
$temp = $data[$left]; | |
$data[$left] = $data[$pivot]; | |
$data[$pivot] = $temp; | |
return $left; | |
} | |
} | |
$sort = new sort(); | |
$data = [4,2,3,7,6,9,1,8,8,9,1,3]; | |
print_r($sort->quicksort($data,0, count($data) - 1)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment