1.快速排序法
- /*快速排序法*/
- function quickSort(a) {
- if (a.length <= 1) {
- return a;
- }
- var midLength = Math.floor(a.length / 2);
- var midValue = a.splice(midLength,1);
- var left = [];
- var right = [];
- for (var i = 0; i < a.length; i++) {
- if (a[i] < midValue) {
- left.push(a[i]);
- } else {
- right.push(a[i]);
- }
- }
- return quickSort(left).concat(midValue,quickSort(right));
- }
- console.log(quickSort([1,5,3,6,2,4,0]));
2.冒泡排序
- /*冒泡排序法*/
- function bubbleSort(a) {
- var length = a.length;
- var sortArray;
- for (var i = 0; i < length-1; i++) {
- for (var j = 0; j < length-i-1 ; j++) {
- if (a[j] > a[j+1]) {
- sortArray = a[j];
- a[j] = a[j+1];
- a[j+1] = sortArray;
- }
- }
- }
- return a;
- }
- console.log(bubbleSort([2,1,3,6,5,4,7,0]));
3.插入排序
- /*插入排序法*/
- function insertSort(a) {
- var length = a.length;
- var sortArray;
- for (var i = 1; i < length; i++) {
- for (var j = 0; j < i ; j++) {
- if (a[i] < a[j]) {
- sortArray = a[i];
- a[i] = a[j];
- a[j] = sortArray;
- }
- }
- }
- return a;
- }
- console.log(insertSort([0,6,5,3,4,2,1,7]));
4.选择排序
- /*选择排序法*/
- function selectSort(a) {
- for (var i = 0; i < a.length; i++) {
- var min = a[i];
- var k = i;
- for (var j = i + 1; j < a.length; j++) {
- if (min > a[j]) {
- min = a[j];
- k = j;
- }
- }
- a[k] = a[i];
- a[i] = min;
- }
- return a;
- }
- console.log(selectSort([5,1,4,0,3,2,7,6]));
附加:js判断滚动条是否到底部
<style>
*{
padding:0;
margin:0;
}
.test{
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
width: 600px;
height: 300px;
padding: 20px;
margin: auto;
overflow-y: auto;
border:2px solid #DDD;
}
</style>
<div class="test" id="test">
<p style="height:400%"></p>
</div>
<script>
var test = document.getElementById("test");
test.addEventListener("scroll", function(){
var str = "可滚动距离:"+ test.scrollHeight +" 滚动位置:"+ test.scrollTop + " 滚动容器高度:"+ test.clientHeight;
var p = document.createElement("p");
p.innerHTML = str;
document.body.appendChild(p);
}, false);
</script>
时间: 2024-10-23 14:13:09