rjangelov

ArraysInPHP - //Problem 4. Selection Sort

Jun 25th, 2014
279
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.19 KB | None | 0 0
  1. //Problem 4.    Selection Sort 
  2. //Sorting an array means to arrange its elements in increasing order. Write a script to sort an array. Use the "selection sort" //algorithm: Find the smallest element, move it at the first position, find the smallest from the rest, move it at the second position, //etc.
  3. //Hint: Use a second array
  4. <!DOCTYPE html>
  5. <html>
  6.     <head>
  7.         <meta charset="UTF-8">
  8.         <title></title>
  9.     </head>
  10.     <body>
  11.         <form action="SelectionSort.php" method="post">
  12.         <input type="text" name="text">
  13.         <input type="submit" value="enter!">
  14.         </form>
  15.     </body>
  16. </html>
  17.  
  18. <?php
  19.  
  20. function selectionSort(array $arr) {
  21.     for ($i = 0; $i < count($arr); $i++) {
  22.         $min = null;
  23.         $minKey = null;
  24.         for($j = $i; $j < count($arr); $j++) {
  25.             if (null === $min || $arr[$j] < $min) {
  26.                 $minKey = $j;
  27.                 $min = $arr[$j];
  28.             }
  29.         }
  30.         $arr[$minKey] = $arr[$i];
  31.         $arr[$i] = $min;
  32.     }
  33.     return $arr;
  34. }
  35. $myString = $_POST['text'];
  36. $myArray=explode(" ", $myString);
  37. $sortedArr = selectionSort($myArray);
  38. echo '<pre>' . print_r($sortedArr, true) . '</pre>';
  39. ?>
Advertisement
Add Comment
Please, Sign In to add comment