Trung vị là giá trị giữa của mảng đã sắp xếp. Nếu mảng có số phần tử lẻ -> lấy phần tử giữa. Nếu chẵn -> lấy trung bình của 2 phần tử giữa.
Ví dụ
Mã tính trung vị cho mảng [1, 5, 6, 99, 12, 11, 22]:
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Tính trung vị mảng</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result, .sample { font-size: 18px; font-weight: 500; color: blueviolet; }
.sample { color: red; }
</style>
</head>
<body>
<h1>Tính trung vị của mảng</h1>
<div><pre class="sample"></pre></div>
<div class="result"></div>
<button class="Btn">TÍNH TRUNG VỊ</button>
<h3>Nhấn nút để tính trung vị mảng trên</h3>
<script>
const resEle = document.querySelector(".result");
const btn = document.querySelector(".Btn");
const sampleEle = document.querySelector(".sample");
const arr = [1, 5, 6, 99, 12, 11, 22];
sampleEle.innerHTML = `[${arr.join(', ')}]`;
btn.addEventListener("click", () => {
const sorted = [...arr].sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
let median;
if (sorted.length % 2 !== 0) {
median = sorted[mid];
} else {
median = (sorted[mid - 1] + sorted[mid]) / 2;
}
resEle.innerHTML = `Trung vị = ${median}`;
});
</script>
</body>
</html>
Kết quả
Mảng gốc: [1, 5, 6, 99, 12, 11, 22]. Sau sắp xếp: [1, 5, 6, 11, 12, 22, 99]. Trung vị = 11 (phần tử giữa).
Cải tiến: Có thể viết thành hàm tái sử dụng function median(arr) {...}.