Bài tập Sử dụng giải thuật sắp xếp chọn (Selection Sort) để sắp xếp các phần tử.

Bạn cũng có thể tìm hiểu về thuật toán này trong bài: Giải thuật sắp xếp chọn (Selection Sort)

PHP script

Dưới đây là phần PHP code để giải bài tập PHP trên:

<html>
   
   <head>
      <title>Giải thuật sắp xếp chọn (Selection Sort) trong PHP</title>
   </head>
   <body>
   
       <?php
        function selection_sort($data)  
		{  
		for($i=0; $i < count($data)-1; $i++) {  
			$min = $i;  
			for($j=$i+1; $j < count($data); $j++) {  
				if ($data[$j] < $data[$min]) {  
					$min = $j;  
				}  
			}  
			$data = swap_positions($data, $i, $min);  
		}  
		return $data;  
		}  
		  
		function swap_positions($data1, $left, $right) {  
			$backup_old_data_right_value = $data1[$right];  
			$data1[$right] = $data1[$left];  
			$data1[$left] = $backup_old_data_right_value;  
			return $data1;  
		}  
		$my_array = array(3, 0, 2, 5, -1, 4, 1);  
		echo "Mảng ban đầu: <br>";  
		echo implode(', ',$my_array );  
		echo "<br>Mảng đã qua sắp xếp:<br>";  
		echo implode(', ',selection_sort($my_array)). PHP_EOL;
       ?>
       
   </body>
</html>

Kết quả

Lưu PHP code trên trong một file có tên là test.php trong htdocs, sau đó mở trình duyệt và gõ địa chỉ http://localhost:8080/test.php sẽ cho kết quả:

Giải thuật sắp xếp chọn (Selection Sort) trong PHP | Bài tập PHP có giải

Các giải thuật sắp xếp trong PHP khác có trên s2sontech:




Bình luận (0)

Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Learning English Everyday