let arr = [1,12,3,65,12,745,88,44];
/**
*
* 冒泡排序是每级筛选出最大的排到最后
*
*/
function Bubbling (arr) {
const length = arr.length;
let state = false; // 位置未进行改变 则循环结束
// 外层遍历arr
for(var i = 0; i < length; i++) {
// 内层针对arr[i] 和 其他进行比对 length-i
for(var j = 0; j < length - i; j++) {
let current = arr[j];
let next = arr[j+1];
let save = '';
if (current > next) {
save = arr[j+1];
arr[j+1] = current;
arr[j] = save;
state = true;
}
}
if (!state) {
console.log('循环结束', i)
return '循环结束'
}
}
console.log('冒泡排序结果:' + arr);
return arr
}
/**
*
* 快速排序
*
*/
function quick (arr) {
// 递归遍历的结束条件
if (arr.length <= 1) {
return arr
}
let left = [], right = [];
const index = Math.floor(arr.length/2);
const base = arr.splice(index, 1)[0];
// 分成左右俩种
for (var i = 0; i < arr.length; i++) {
if (arr[i] < base) {
left.push(arr[i])
} else {
right.push(arr[i])
}
}
let newArr = quick(left).concat([base], quick(right));
console.log('快速排序的结果:' + newArr)
return newArr
}
/**
*
* 递归算法 斐波那契数列
*
*/
function recursion (num) {
if (num <= 2 ) {
return 1
}
//console.log(num);
return recursion(num-1) + recursion(num - 2)
}
Bubbling(arr); // 冒泡排序
quick(arr); // 快速排序
console.log(recursion(6)) // 斐波那契
// 测试城市升级联动
/**
*
* 省市区遍历
*
*/
// 深度遍历
function loop (data, Keyword, num) {
// debugger
let option = [];
if (Keyword) {
data.forEach(item => {
const map = obj => {
// debugger
if (typeof obj.name == "undefined") {
return
}
if (obj.name == Keyword){
option = obj.city || obj.area;
return
}
const newObj = obj.city || obj.area;
newObj.forEach(child => map(child))
}
map(item);
})
// 层级判断 存在北京同级
if (num == 3 && option.length == 1) {
option = backArr(option[0].area)
} else {
if (typeof option[0] != "string") {
option = backArr(option, 'name');
}
}
} else {
option = backArr(data, 'name');
}
return option;
}
// 遍历并返回新数组
function backArr (data, name) {
// 遍历数组 并返回data.name
const op = data.map(item => {
if (name) return item[name];
return item
})
return op;
}
// 添加option
function addOption (dom,data) {
dom.options.length = 0;
data.forEach(item => {
dom.add(new Option(item,item))
})
}
const Province = document.querySelector('#Province'),
citys = document.querySelector('#city'),
area = document.querySelector('#area')
// console.log(loop(city, '石家庄', 3));
function createOption(p, dom) {
if (typeof p == "undefined") {
addOption(Province, loop(city));
addOption(citys, loop(city, '北京', 2));
addOption(area, loop(city, '北京', 3));
return
}
if (dom == citys) {
addOption(dom, loop(city, p));
const text = dom.options[0].text;
addOption(area, loop(city, text));
} else {
addOption(dom, loop(city, p));
}
}
createOption()
// 省份变化
Province.addEventListener('change', function() {
let index = this.selectedIndex, text = this.options[index].text;
console.log(text);
createOption(text, citys);
})
// 城市变化
citys.addEventListener('change', function() {
let index = this.selectedIndex, text = this.options[index].text;
console.log(text);
createOption(text, area);
})