Answer the question
In order to leave comments, you need to log in
Why does my quicksort work in a non-obvious way?
Hello, I'm studying algorithms in the book "Groaking Algorithms", I write in PHP, now I've reached quick sorting. It seems to me that I more or less understand the principle of the algorithm, however, I cannot understand what is wrong. Here is the working code:
function testsort(array $array) {
if (count($array) < 2) {
return $array;
}
$elem = [$array[0]];
$left = [];
$right = [];
for ($i = 1; $i < count($array); $i++) {
if ($array[$i] <= $elem[0]) {
$left[] = $array[$i];
} else {
$right[] = $array[$i];
}
}
return array_merge(testsort($left), $elem, testsort($right));
}
$elem = [$array[rand(0, count($array) - 1)]];
array (size=6)
0 => int 3
1 => int 3
2 => int 3
3 => int 4
4 => int 5
5 => int 5
Answer the question
In order to leave comments, you need to log in
Everything was solved in an elementary way, as I understand it, the cycle reached an iteration, where 2-3 elements remained in the array and broke, because the iteration of the reference element was also included in the cycle. As a result, just explicitly telling the cycle to go further when it reaches the pivot, the problem was solved and everything was sorted. So that it does not filter out the same ones, I created a $temp variable, which serves as a marker if this element has already been iterated over.
function testsort(array $array) {
if (count($array) < 2) {
return $array;
}
$elem = [$array[(int)count($array) / 2]];
$left = [];
$right = [];
$temp = '';
for ($i = 0; $i < count($array); $i++) {
if ($array[$i] < $elem[0]) {
$left[] = $array[$i];
}
if ($array[$i] > $elem[0]) {
$right[] = $array[$i];
}
if ($array[$i] == $elem[0]) {
if ($temp) {
$left[] = $array[$i];
} else {
$temp = $elem[0];
continue;
}
}
}
return array_merge(testsort($left), $elem, testsort($right));
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question