冒泡排序
冒泡排序就是两个for循环比较相邻的大小,根据大小来排位置,两个for循环搞定。
const array = [2, 334, 54, 3, 23, 12, 32]
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length - i - 1; j++) {
if (array[j] > array[j + 1]) {
const temp = array[j + 1]
array[j + 1] = array[j]
array[j] = temp
}
}
}
console.log(array);
快速排序
快速排序选择随机一个位置作为基点,将以这个基点为中心根据大小左右排序,并且通过递归的方式将左右切成最少有一位数的数组,完成排序
const array = [21, 32, 343, 4, 35, 4, 42, 32, 3, 23, 4, 34, 312, 234]
function quickSort(arr) {
if (arr.length <= 1) return arr
let left = [], right = [], mid = arr.splice(0, 1)
for (let index = 0; index < arr.length; index++) {
const element = arr[index];
if (element < mid) {
left.push(element)
} else {
right.push(element)
}
}
return quickSort(left).concat(mid, quickSort(right))
}
console.log(quickSort(array));
插入排序
插入排序实际上将数组每一项给抽离出来,跟已经排好序的数组进行对比,将每一项插入到排好序的数组内
function sort(array) {
for (let i = 1; i < array.length; i++) {
for (let j = i; j > 0; j--) {
if (array[j] < array[j - 1]) {
[array[j], array[j - 1]] = [array[j - 1], array[j]]
} else {
break
}
}
}
return array
}
选择排序
选择排序就是将一串数组中找出最小的那一位排列到最前或者最后一个位置,然后再从剩下的数中找出最小的数继续放在第二位,以此类推
const array = [212, 323, 4, 21, 32, 43, 43, 12, 34, 4, 2343]
function selectSort(array) {
const length = array.length
var minIndex, temp
for (let i = 0; i < length; i++) {
minIndex = i
for (let j = i + 1; j < length; j++) {
if (array[minIndex] > array[j]) {
minIndex = j
}
}
temp = array[i]
array[i] = array[minIndex]
array[minIndex] = temp
}
return array
}
console.log(selectSort(array));