一 冒泡排序

在这里插入图片描述

1.1 算法解析

  • 比较相邻的元素。如果第一个比第二个大,就交换他们两个。
  • 每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。这步做完后,最后的元素会是最大的数。
  • 重复以上的步骤 直到没有任何一对数字需要比较

1.2 代码展示

class sortSelf extends Array{
	...
	bubbleSort(){
        // O(n^2) O(1)
        for(let j = 1; j < this.length; j++){
            for(let i = 0; i < this.length-j; i++){
                if(this[i]>this[i+1]){
                    ([this[i+1],this[i]] = [this[i],this[i+1]]);
                }
            }
        }
    }
    ...
}
let res = new sortSelf(2,5,4,3);
res.bubbleSort(); // res改变

二 选择排序

在这里插入图片描述

2.1 算法解析

  • 在未排序序列中找到最小(大)元素,存放到排序序列的起始/末尾位置。

2.2 代码展示

class sortSelf extends Array{
	... ...
	selectionSort(){
        // O(n^2) O(1)
        for(let j = 0; j < this.length; j++){
            let min = this[j];
            let minIndex = j;
            for(let i = j; i < this.length; i++){
                minIndex = min > this[i]? i: minIndex;
                min = this[minIndex];
            }
            ([this[j],this[minIndex]] = [this[minIndex],this[j]]);
        }
    }
    ... ...
}
let res = new sortSelf(2,5,4,3);
res.selectionSort(); // res改变

三 插入排序

在这里插入图片描述

3.1 算法解析

  • 从头到尾依次扫描未排序序列,将扫描到的每个元素插入有序序列的适当位置。

3.2 代码展示

class sortSelf extends Array{
	... ...
	insertionSort(){
        // O(n^2) O(1)
        for(let j = 0; j < this.length; j++){
            for(let i = 0; i < j; i++){
                if(this[i]>this[j]){
                    this.splice(i, 0, this[j]);
                    this.splice(j+1, 1);
                    break;
                }
            }
        }    
    }
    ... ...
}
let res = new sortSelf(2,5,4,3);
res.insertionSort(); // res改变

四 归并排序

4.1 算法解析

在这里插入图片描述

  • 该算法是采用分治法(Divide and Conquer)的一个非常典型的应用
  • 将排序序列递归等分为两个数列直到两个数列长度为1为止。
  • 将两个数列合并为有序数列,层层返回,直到整个序列有序。

4.2 代码展示

class sortSelf extends Array{
	... ...
	static mergeSort(arr){
        // O(nlogn) O(n)
        if(arr.length < 2){
            return arr;
        }else {
            var mid = Math.floor(arr.length/2);
        }
        return this.merge(this.mergeSort(arr.slice(0,mid)),
                          this.mergeSort(arr.slice(mid)));
    }
    static merge(arr1, arr2){
        let res = [];
        for(var i = 0, j = 0; i < arr1.length && j < arr2.length;){
            arr1[i]<=arr2[j]? res.push(arr1[i++]): res.push(arr2[j++]);
        }
        while(i < arr1.length){
            res.push(arr1[i++])
        }
        while(j < arr2.length){
            res.push(arr2[j++])
        }
        return res;
    }
    ... ...
}

sortSelf.mergeSort([2,5,4,3]); // 返回值返回结果
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐