递归找最小
let min = (numbers) => {
if (numbers.length > 2) {
return min(
[numbers[0], min(numbers.slice(1))]
)
} else {
return Math.min.apply(null, numbers)
}
}
递归排序
let min = (numbers) => {
if (numbers.length > 2) {
return min(
[numbers[0], min(numbers.slice(1))]
)
} else {
return Math.min.apply(null, numbers)
}
}
let sort = (numbers) => {
if (numbers.length > 2) {
let index = minIndex(numbers)
let min = numbers[index]
numbers.slice(index, 1)
return [min].concat(sort(numbers))
} else {
return numbers[0] < numbers[1] ? numbers[0] : numbers.reverse()
}
}
选择排序
let sort = (numbers) => {
for (let i = 0; i < numbers.length - 1; i++) {
let index = minIndex(numbers.slice(i)) + i
if (index !== i) {
swap(numbers, index, i)
}
}
return numbers
}
let swap = (array, i, j) => {
let temp = array[i]
array[i] = array[j]
array[j] = temp
}
let minIndex = (numbers) => {
let index = 0
for (let i = 1; i < numbers.length; i++) {
if (numbers[i] < numbers[index]) {
index = i
}
}
return index
}
快速排序
let quickSort = arr => {
if (arr.length <= 1) {
return arr
}
let pivotIndex = Math.floor(arr.length / 2)
let pivot = arr.slice(pivotIndex, 1)[0] //[0]的作用是把数组变成数
let left = []
let right = []
for (let i = 0; i < arr.length; i++) {
if (arr[i] < pivot) {
left.push(arr[i])
} else {
right.push(arr[i])
}
}
return quickSort(left).concat([pivot], quickSort(right))
}
归并排序
let mergeSort = arr => {
if (arr.length === 1) {
return arr
}
let left = arr.slice(0, Math.floor(arr.length / 2))
let right = arr.slice(Math.floor(arr.length / 2))
return merge(mergeSort(left), mergeSort(right))
}
let merge = (a, b) => {
if (a.length === 0) {
return b
}
if (b.length === 0) {
return a
}
return a[0] > b[0] ? [b[0]].concat(merge(a, b.slice(1))) : [a[0]].concat(merge(b, a.slice(1)))
}
计数排序
let countSort = arr =>{
let hashTable={},max=0,result=[]
for (let i=0;i<arr.lenght;i++){
if(!(arr[i] in hashTable)){
hashTable[arr[1]]=1
}else{
hashTable[arr[1]]+=1
}
if(arr[i]>max){max=arr[i]}
}
for(let j=0;j<=max;j++){
if(j in hashTable){
result.push(j)
}
}
return result
}