Advertisement
Zarna0x

PHP SelectionSort Implementation

Apr 28th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.47 KB | None | 0 0
  1. <?php
  2.  
  3.  
  4. class SelectionSort
  5. {
  6.   protected $_sortedArray;
  7.  
  8.   public function __construct($Arr)
  9.   {
  10.     if (!is_array($Arr)) {
  11.        return "Param must be array";
  12.     }
  13.    
  14.     for ($i = 0; $i < count($Arr); $i++) {
  15.        $min  = $this->findMinIndex($Arr,$i); // = 3
  16.        $Arr =  $this->swapPositions($Arr,$i,$min);
  17.     }
  18.  
  19.     $this->_sortedArray = $Arr;
  20.   }
  21.   public function get()
  22.   {
  23.     return $this->_sortedArray;
  24.   }
  25.  
  26.   public function findMinIndex($ArrData,$offset)
  27.   {
  28.      $min = $offset;
  29.      for ($I = $offset; $I < count($ArrData); $I++) {
  30.        if ($ArrData[$I] < $ArrData[$min]) {
  31.             $min = $I;
  32.         }
  33.      }
  34.  
  35.      return $min;
  36.   }
  37.  
  38.   protected function swapPositions($swapArray,$i,$min)
  39.   {
  40.      $temp = $swapArray[$i];
  41.      $swapArray[$i] = $swapArray[$min];
  42.      $swapArray[$min] = $temp;
  43.  
  44.      return $swapArray;
  45.   }
  46.  
  47. }
  48.  
  49. $sorted = new SelectionSort([
  50.   5,7,9,1,3,15
  51. ]);
  52.  
  53. var_dump($sorted->get());
  54.  
  55.  
  56. // function SelectionSort($arr)
  57. // {
  58. //   for ($i = 0; $i < count($arr); $i++) {
  59. //      $min = $i;
  60. //      //find index of minimum value
  61. //      for ( $j = $min + 1; $j < count($arr); $j++) {
  62. //         if ($arr[$j] < $arr[$min]) {
  63. //             $min = $j;
  64. //         }
  65. //      }
  66.  
  67. //      // Swap
  68. //      $temp = $arr[$i];
  69. //      $arr[$i] = $arr[$min];
  70. //      $arr[$min] = $temp;
  71.  
  72. //   }
  73.  
  74. //   return $arr;
  75. // }
  76.  
  77.  
  78. // $newArr = SelectionSort([
  79. //   5,7,9,1,3,15
  80. // ]);
  81.  
  82. // var_dump($newArr);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement