<!DOCTYPE html>
<html>
	<head>
		<title>JavaScript实现可视化展示冒泡排序过程</title>
		<style>
			#boxes{
				border:1px solid grey;
				width:1320px;
				height:300px;
				margin-top:10px;
				position:relative;
			}
			.box{
				background:red;
				width:20px;
				line-height:30px;
				text-align:center;
				font-family:Microsoft Yahei;
				font-size:15px;
				color:white;
				margin:0 1px;
				position:absolute;
			}
		</style>
	</head>
	<body>
		<div id="boxes"></div>
		<script>
			function random(){
				var numbers = [];
				for (var i = 0; i < 60; i++) {
					var number = Math.floor(Math.random() * 90 + 10);
					numbers.push(number);
					var divElement = document.createElement("div");
					var parentElement = document.getElementById("boxes");
					divElement.style.left = i * 20 + i * 2 + "px";
					divElement.style.top = 300 - 3 * number + "px";
					divElement.style.height = 3 * number + "px";
					divElement.setAttribute("class","box");
					parentElement.appendChild(divElement);
				}
				return numbers;
			}
			function sort(){
				var numbers = random();
				var parentElement = document.getElementById("boxes");
				var i = 0, j = 0;
				var time = setInterval(function() {
					if (i < numbers.length) {
						if (j < numbers.length - i) {
							if (numbers[j] > numbers[j + 1]) {
								var temp = numbers[j];
								numbers[j] = numbers[j + 1];
								numbers[j + 1] = temp;
								parentElement.innerHTML = "";
								for (var k = 0; k < numbers.length; k++) {
									var textNode = document.createTextNode(numbers[k]);
									var divElement = document.createElement("div");
									divElement.appendChild(textNode);
									divElement.style.left = k * 20 + k * 2 + "px";
									divElement.style.top = 300 - 3 * numbers[k] + "px";
									divElement.style.height = 3 * numbers[k] + "px";
									divElement.setAttribute("class","box");
									parentElement.appendChild(divElement);
								}
							}
							j++;
						}
						else{
							i++;
							j = 0;
						}
					}
					else {
						clearInterval(time); 
						return;
					}
				}, 100);  
			}
			sort();
		</script>
	</body>
</html>


本文转载:CSDN博客