Javascript - Sắp xếp một mảng bằng phương pháp Bubble Sort
Sắp xếp một mảng bằng phương pháp Bubble Sort
Lưu ý: Sắp xếp theo Bubble là một thuật toán sắp xếp đơn giản hoạt động bằng cách lặp đi lặp lại việc lướt qua danh sách được sắp xếp.
Ví dụ:
Nhập: [6,4,0, 3,-2,1]
Kết quả : [-2, 0, 1, 3, 4, 6]
Mã nguồn:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Bubble Sort</title>
<script>
Array.prototype.bubbleSort_algo = function()
{
var is_sorted = false;
while (!is_sorted)
{
is_sorted = true;
for (var n = 0; n < this.length - 1; n++)
{
if (this[n] > this[n+1]){
var x = this[n+1];
this[n+1] = this[n];
this[n] = x;
is_sorted = false;
}
}
}
return this;
};
document.write([6,4,0, 3,-2,1].bubbleSort_algo());
</script>
</head>
<body>
</body>
</html>
Lưu đồ thuật toán: