前端常用排序算法模块化实现 (冒泡 | 选择 | 插入 | 归并)

一 冒泡排序

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]); // 返回值返回结果

你可能感兴趣的:(JS,排序算法,插入排序,数据结构,javascript)