Blog

It's a Wonderful Life

比较简洁的冒泡排序算法实现

2016-08-24 21:00 Posted in Learn with HTML , JavaScript , algorithm

今天看到一个蛮有趣的冒泡算法,逻辑很清晰,忍不住记在博客里面,代码如下:

<!DOCTYPE html>
<html>
	<head>
		<meta charset-utf-8>
		<title>bubble</title>
		<script>
			var arr = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
			var n = arr.length - 1
			
			for(sorted = false; sorted = !sorted; n--) {
				for(j = 0; j < n; j++) {
					if(arr[j] > arr[j + 1]) {
						var temp = arr[j]
						arr[j] = arr[j + 1]
						arr[j + 1] = temp
						sorted = false;
					}
				}
			}
			
			document.write(arr)
		</script>
	</head>
</html>