Skip to content

Commit 6f9768b

Browse files
committed
added sort method to arrayList
1 parent 1a2f6ec commit 6f9768b

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

src/Datastructure/Lists/ArrayLists/ArrayList.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
namespace doganoo\PHPAlgorithms\Datastructure\Lists\ArrayLists;
2727

2828

29+
use doganoo\PHPAlgorithms\Algorithm\Sorting\TimSort;
2930
use doganoo\PHPAlgorithms\Common\Exception\IndexOutOfBoundsException;
3031
use doganoo\PHPAlgorithms\Common\Interfaces\IComparable;
3132
use doganoo\PHPAlgorithms\Common\Util\Comparator;
@@ -426,4 +427,20 @@ public function compareTo($object): int {
426427
}
427428
return -1;
428429
}
430+
431+
/**
432+
* @return bool
433+
*/
434+
public function sort(): bool {
435+
$array = \array_filter($this->array, function ($value, $key) {
436+
return $value !== null;
437+
}, \ARRAY_FILTER_USE_BOTH);
438+
439+
440+
$timSort = new TimSort();
441+
$array = $timSort->sort($array);
442+
$this->array = \array_fill(0, self::DEFAULT_CAPACITY, null);
443+
$this->addAllArray($array);
444+
return true;
445+
}
429446
}

tests/Lists/ArrayLists/ArrayListTest.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,4 +218,21 @@ public function testSerialize() {
218218
$this->assertTrue(null !== $list && $list instanceof stdClass);
219219
}
220220

221+
public function testSort() {
222+
$arrayList = new ArrayList();
223+
$arrayList->add(3);
224+
$arrayList->add(2);
225+
$arrayList->add(5);
226+
$arrayList->add(1);
227+
$arrayList->add(4);
228+
229+
$arrayList->sort();
230+
231+
$this->assertTrue(1 === $arrayList->get(0));
232+
$this->assertTrue(2 === $arrayList->get(1));
233+
$this->assertTrue(3 === $arrayList->get(2));
234+
$this->assertTrue(4 === $arrayList->get(3));
235+
$this->assertTrue(5 === $arrayList->get(4));
236+
}
237+
221238
}

0 commit comments

Comments
 (0)