From 3a1c09cac477e4ebd82c12e457d2fd5cc6016d1c Mon Sep 17 00:00:00 2001 From: Tushar <100490977+tusharnain4578@users.noreply.github.com> Date: Wed, 2 Oct 2024 20:35:17 +0530 Subject: [PATCH] Create BogoSort.php Added BogoSort --- Sorting/BogoSort.php | 47 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Sorting/BogoSort.php diff --git a/Sorting/BogoSort.php b/Sorting/BogoSort.php new file mode 100644 index 00000000..06bc3866 --- /dev/null +++ b/Sorting/BogoSort.php @@ -0,0 +1,47 @@ +array = $array; + } + + // Method to check if the array is sorted + private function isSorted(): bool { + $count = count($this->array); + for ($i = 0; $i < $count - 1; $i++) { + if ($this->array[$i] > $this->array[$i + 1]) { + return false; + } + } + return true; + } + + // Method to shuffle the array + private function shuffleArray(): void { + shuffle($this->array); // Built-in PHP shuffle function + } + + // Method to sort the array using Bogo Sort + public function sort(): array { + while (!$this->isSorted()) { + $this->shuffleArray(); + } + return $this->array; + } + + // Method to get the sorted array + public function getSortedArray(): array { + return $this->sort(); + } +} + +// Example usage: +$array = [3, 1, 4, 1, 5]; +$bogoSort = new BogoSort($array); + +$sortedArray = $bogoSort->getSortedArray(); +print_r($sortedArray);