Giải thuật sắp xếp trộn (Merge Sort) trong PHP
Bài tập Sử dụng giải thuật sắp xếp trộn (Merge 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 trộn (Merge 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 trộn (Merge Sort) trong PHP</title>
</head>
<body>
<?php
function merge_sort($my_array){
if(count($my_array) == 1 ) return $my_array;
$mid = count($my_array) / 2;
$left = array_slice($my_array, 0, $mid);
$right = array_slice($my_array, $mid);
$left = merge_sort($left);
$right = merge_sort($right);
return merge($left, $right);
}
function merge($left, $right){
$res = array();
while (count($left) > 0 && count($right) > 0){
if($left[0] > $right[0]){
$res[] = $right[0];
$right = array_slice($right , 1);
}else{
$res[] = $left[0];
$left = array_slice($left, 1);
}
}
while (count($left) > 0){
$res[] = $left[0];
$left = array_slice($left, 1);
}
while (count($right) > 0){
$res[] = $right[0];
$right = array_slice($right, 1);
}
return $res;
}
$test_array = array(100, 54, 7, 2, 5, 4, 1);
echo "Mảng ban đầu:<br>";
echo implode(', ',$test_array );
echo "<br>Mảng đã qua sắp xếp:<br>";
echo implode(', ',merge_sort($test_array))."<br>";
?>
</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ả:
Các giải thuật sắp xếp trong PHP khác có trên VietJack:
Công cụ giáo viên (2048.VN)
Tạo- trộn đề thi miễn phí từ file PDF, Word, Giao bài nhanh chóng, Hoàn toàn Free
Follow fanpage của team https://www.facebook.com/vietjackteam/ hoặc facebook cá nhân Nguyễn Thanh Tuyền https://www.facebook.com/tuyen.vietjack để tiếp tục theo dõi các loạt bài mới nhất về Ngữ pháp tiếng Anh, luyện thi TOEIC, PHP, Java, C, C++, Javascript, HTML, Python, Database, Mobile ... mới nhất của chúng tôi.

