Skip to content

Instantly share code, notes, and snippets.

@sagittaracc
Created November 18, 2022 07:26
Show Gist options
  • Save sagittaracc/fa4616bc38734c592e67dabccc5a4f34 to your computer and use it in GitHub Desktop.
Save sagittaracc/fa4616bc38734c592e67dabccc5a4f34 to your computer and use it in GitHub Desktop.
PHP Sort
<?php
class Soldier
{
private $name;
private $height;
public function __construct($name)
{
$this->name = $name;
}
public function setHeight(int $height)
{
$this->height = $height;
}
public function getHeight()
{
return $this->height;
}
public function __toString()
{
return "{$this->name}: {$this->height}";
}
}
class Line
{
private $line = [];
public function add(Soldier $soldier)
{
$this->line[] = $soldier;
return $this;
}
public function sort()
{
for ($j = 0; $j < count($this->line) - 1; $j++) {
for ($i = 0; $i < count($this->line) - $j - 1; $i++) {
if ($this->line[$i]->getHeight() > $this->line[$i + 1]->getHeight()) {
$tmp_var = $this->line[$i + 1];
$this->line[$i + 1] = $this->line[$i];
$this->line[$i] = $tmp_var;
}
}
}
}
public function print()
{
foreach ($this->line as $soldier) {
echo $soldier . "\n";
}
}
}
$vova = new Soldier('Vova');
$vova->setHeight(165);
$vitya = new Soldier('Vitya');
$vitya->setHeight(164);
$petr = new Soldier('Petr');
$petr->setHeight(190);
$line = new Line();
$line
->add($vova)
->add($vitya)
->add($petr);
$line->sort();
$line->print();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment