Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Problem 4. Selection Sort
- //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.
- //Hint: Use a second array
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title></title>
- </head>
- <body>
- <form action="SelectionSort.php" method="post">
- <input type="text" name="text">
- <input type="submit" value="enter!">
- </form>
- </body>
- </html>
- <?php
- function selectionSort(array $arr) {
- for ($i = 0; $i < count($arr); $i++) {
- $min = null;
- $minKey = null;
- for($j = $i; $j < count($arr); $j++) {
- if (null === $min || $arr[$j] < $min) {
- $minKey = $j;
- $min = $arr[$j];
- }
- }
- $arr[$minKey] = $arr[$i];
- $arr[$i] = $min;
- }
- return $arr;
- }
- $myString = $_POST['text'];
- $myArray=explode(" ", $myString);
- $sortedArr = selectionSort($myArray);
- echo '<pre>' . print_r($sortedArr, true) . '</pre>';
- ?>
Advertisement
Add Comment
Please, Sign In to add comment