1、冒泡排序
说明:
- 比较所有相邻元素,如果第一个比第二个大,则交换它们
- 一轮下来保证可以找到一个数是最大的
- 执行n-1轮,就可以完成排序
实例:
var arr = [1,9,89,0,34,27,10];
Array.prototype.bubbleSort = function(){
for(let i = 0;i < this.length - 1;i++){
for(let j = 0;j < this.length - 1 - i;j++){
if(this[j] > this[j+1]){
const temp = this[j];
this[j] = this[j+1];
this[j+1] = temp;
}
}
}
}
arr.bubbleSort();
document.write(arr);
2、选择排序
说明:
- 设置第一位为最小数值
- 从i+1遍历寻找小于它的数,改变indexMin,并交换数值
实例:
Array.prototype.selectionSort = function(){
for(let i = 0;i < this.length - 1;i++){
let indexMin = i;
for(let j = i + 1;j < this.length;j++){
// 找到小于当前数值的下标,下标设置j,交换数值
if(this[i] > this[j]){
indexMin = j;
const temp = this[i];
this[i] = this[indexMin];
this[indexMin] = temp;
}
}
}
}
arr.selectionSort();
document.write(arr);
3、插入排序
说明:
- 从第二个数开始往前比
- 比它大就往后排
- 以此类推进行到最后一个数
实例:
Array.prototype.insertionSort = function(){
// 从第二个数开始往前比
for(let i = 1;i < this.length;i++){
// 先把值保存起来
const temp = this[i];
let j = i;
while(j > 0){
if(temp < this[j-1]){
this[j] = this[j-1];
}else{
break;
}
j -= 1;
}
// 这里的j有可能是第0位,也有可能是到了一半停止了
this[j] = temp;
}
}
4、归并排序
说明:
分: 把数组劈成两半,再递归地对数组进行“分”操作,直到分成一个个单独的数
合:把两个数合并为有序数组,再对有序数组进行合并,直到全部子数组合并为一个完整数组
实例:
Array.prototype.mergeSort = function () {
const rec = (arr) => {
//如果数组长度为1,说明切完了,可以直接返回
if (arr.length === 1) { return arr; }
//切分数组,把每一项都单独切出来
const mid = Math.floor(arr.length / 2);
const left = arr.slice(0,mid);
const right = arr.slice(mid,arr.length);
//有序的左边数组
const orderLeft = rec(left);
//有序的右边数组
const orderRight = rec(right);
//定义一个数组来存放顺序数组
const res = [];
// 把左右两个有序的合并为一个有序的返回
while(orderLeft.length || orderRight.length) {
if(orderLeft.length && orderRight.length) {
res.push(orderLeft[0] < orderRight[0] ? orderLeft.shift() : orderRight.shift())
} else if (orderLeft.length) {
res.push(orderLeft.shift());
} else if (orderRight.length) {
res.push(orderRight.shift());
}
}
return res;
};
const res = rec(this);
//拷贝到数组本身
res.forEach((n,i) => { this[i] = n; });
}
arr.mergeSort();
document.write(arr);
5、快速排序
说明:
分区: 从数组中任意选择一个基准,所有比基准小的元素放到基准前面,比基准大的元素放到基准的后面
递归:递归地对基准前后的子数组进行分区
实例:
Array.prototype.quickSort = function () {
const rec = (arr) => {
// 预防数组是空的或者只有一个元素, 当所有元素都大于等于基准值就会产生空的数组
if(arr.length === 1 || arr.length === 0) { return arr; }
const left = [];
const right = [];
//以第一个元素作为基准值
const mid = arr[0];
//小于基准值的放左边,大于基准值的放右边
for(let i = 1; i < arr.length; ++i) {
if(arr[i] < mid) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
//递归调用,最后放回数组
return [...rec(left),mid,...rec(right)];
};
const res = rec(this);
res.forEach((n,i) => { this[i] = n; })
}
const arr = [2,3,4,5,3,1];
arr.quickSort();
console.log(arr);