Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class SelectionSort
- {
- protected $_sortedArray;
- public function __construct($Arr)
- {
- if (!is_array($Arr)) {
- return "Param must be array";
- }
- for ($i = 0; $i < count($Arr); $i++) {
- $min = $this->findMinIndex($Arr,$i); // = 3
- $Arr = $this->swapPositions($Arr,$i,$min);
- }
- $this->_sortedArray = $Arr;
- }
- public function get()
- {
- return $this->_sortedArray;
- }
- public function findMinIndex($ArrData,$offset)
- {
- $min = $offset;
- for ($I = $offset; $I < count($ArrData); $I++) {
- if ($ArrData[$I] < $ArrData[$min]) {
- $min = $I;
- }
- }
- return $min;
- }
- protected function swapPositions($swapArray,$i,$min)
- {
- $temp = $swapArray[$i];
- $swapArray[$i] = $swapArray[$min];
- $swapArray[$min] = $temp;
- return $swapArray;
- }
- }
- $sorted = new SelectionSort([
- 5,7,9,1,3,15
- ]);
- var_dump($sorted->get());
- // function SelectionSort($arr)
- // {
- // for ($i = 0; $i < count($arr); $i++) {
- // $min = $i;
- // //find index of minimum value
- // for ( $j = $min + 1; $j < count($arr); $j++) {
- // if ($arr[$j] < $arr[$min]) {
- // $min = $j;
- // }
- // }
- // // Swap
- // $temp = $arr[$i];
- // $arr[$i] = $arr[$min];
- // $arr[$min] = $temp;
- // }
- // return $arr;
- // }
- // $newArr = SelectionSort([
- // 5,7,9,1,3,15
- // ]);
- // var_dump($newArr);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement