这里用 js+ vue写, 方便页面展示效果,每段代码直接放html即可执行。持续更新。
写代码之前,最好先理解对应排序的原理。
- 冒泡排序
- 快速排序 (效果图不好展示,可以在console打印查看)
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>测试用</title>
<meta name="keywords" content="">
<meta name="description" content="">
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="format-detection" content="telephone=no">
<meta HTTP-EQUIV="pragma" CONTENT="no-cache">
<meta HTTP-EQUIV="Cache-Control" CONTENT="no-store, must-revalidate">
<meta HTTP-EQUIV="expires" CONTENT="Wed, 26 Feb 1997 08:21:57 GMT">
<meta HTTP-EQUIV="expires" CONTENT="0">
<style>
.f0 {
background-color: #9c9d9d;
position: relative;
top: 100px;
}
.f1 {
width: 50px;
float: left;
background-color: #2d8cf0;
border: 1px solid darkolivegreen;
position: absolute;
bottom: 0;
}
.btn {
float: right;
}
</style>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="app">
<div class="f0">
<div class="f1" v-for="(item1, index1) in arr" :key="'a' + item1"
:style="{'height': item1*10+'px', 'margin-left': index1*50 + 'px'}">{{item1}}
</div>
<div class="btn">
<p>
<button @click="ff(1)">just do it 冒泡排序</button>
</p>
<p>
<button @click="ff(2)">just do it 快速排序</button>
</p>
</div>
</div>
</div>
</body>
<script>
new Vue({
el: '#app',
data () {
return {
arr: [5, 10, 1, 3, 9, 7, 8, 6, 4, 2],
arr2: [],
arr3: [],
numAll: 0
}
},
methods: {
ff (data) {
this.arr = [5, 10, 1, 3, 9, 7, 8, 6, 4, 2]
if (data == 1) {
this.f1()
} else if (data == 2) {
this.f2(this.arr)
}
},
/**
* 冒泡排序
*/
f1 () {
let arr = this.arr.map(item => item)
let count = arr.length - 1
let count1 = count
let arr1 = []
for (let j = 0; j < count; j++) {
for (let i = 0; i < count1; i++) {
if (arr[i] > arr[i + 1]) {
let hhh = arr[i + 1]
arr[i + 1] = arr[i]
arr[i] = hhh
arr1.push(arr.map(item1 => item1))
}
}
count1--
}
this.ys(arr1)
},
/**
* 快速排序
*/
f2 (arr) {
if (arr.length === 1) {
this.arr2.push(arr[0])
this.ys (this.arr2.map(item2 => item2))
return false;
}
// if (arr.length >= 2) {
let sum = arr.reduce((sum, val) => {
return sum + val
}, 0)
let num = sum / (arr.length)
let arr1 = []
let arr2 = []
arr.forEach(item => {
if (num > item) {
arr1.push(item)
} else {
arr2.push(item)
}
})
let arr3 = [arr1, arr2]
console.log(arr1.concat(arr2))
arr3.forEach(item1 => {
this.f2(item1)
})
// }
},
/**
* 延时展示效果
*/
ys (arr) {
let num = 0
let count = arr.length - 1
let timeId = setInterval(() => {
this.arr = arr[num]
if (num++ === count) {
clearInterval(timeId)
}
}, 1000)
}
}
})
</script>
</html>