<html>
<div>
冒泡排序,数组去重,回文,字符串中出现次数最多的字符
</div>
<script>
// 冒泡排序:
function bubbleSort(arr) {
let len = arr.length
for (let i = 1; i < len - 1; i++) {
for (let j = 0; j < len - i; j++) {
if (arr[j] > arr[j + 1]) {
let temp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = temp
}
}
}
console.log("冒泡排序:", arr)
}
// 快速排序:
function qSort(arr) {
let base = arr[0]
let left = []
let right = []
if (arr.length <= 1) return arr
for (let n = 1; n < arr.length; n++) {
if (arr[n] <= base) {
left.push(arr[n])
} else {
right.push(arr[n])
}
}
return [...qSort(left), ...[base], ...qSort(right)]
}
console.log('快速排序:', qSort([1, 3, 2, 4, 6, 5]))
let arr = [1, 3, 2, 4, 6, 3, 5, 3]
bubbleSort(arr)
// 数组去重
function uniqueArray(arr) {
let temp = []
for (let n in arr) {
if (temp.indexOf(arr[n]) == -1) {
temp.push(arr[n])
}
}
console.log('数组去重:', temp)
return temp
}
uniqueArray([1, 1, 2, 2, 3, 4])
console.log('set数组去重', Array.from(new Set([1, 1, 2, 2, 3, 4])))
function palindrome(str) {
let str1 = str.split('').reverse()
console.log("回文", str1, str == str1.join(''))
return str == str1.join('')
}
palindrome('1221')
// 字符串中出现次数最多的字符
function findMax(str) {
let ci = {}
let max = ''
let c = ''
for (let n in str) {
if (!ci[str[n]]) {
ci[str[n]] = 1
} else {
ci[str[n]]++
}
if (max == '' || ci[str[n]] > max) {
max = ci[str[n]]
c = str[n]
}
}
console.log('出现次数最多的字符以及次数是:', c, max)
return max
}
findMax('ssssswwwwwweeerrrrrrrre')
function deepCopy(obj) {
if (typeof obj != 'object') return
let newObj = obj instanceof Array ? [] : {}
for (let n in obj) {
if (obj.hasOwnProperty(n)) {
newObj[n] = typeof obj[n] == 'object' ? deepCopy(obj[n]) : obj[n]
}
}
return newObj
}
console.log("深拷贝:", deepCopy({
name: '123',
person: {
age: 2
}
}))
</script>
</html>