一、冒泡排序
冒泡排序就是简单的两两对比,每次循环都将当前最大的数放在最右边。
比较和交换的复杂度都为O(N²)
// 冒泡排序bubbleSort() {const length = this.arr.length;for (let i = length - 1; i >= 0; i--) {for (let j = 0; j < i; j++) {if (this.arr[j] > this.arr[j + 1]) {this.swap(j, j + 1);}}}}
二、选择排序
选择排序:用一个变量存储当前较小的那个元素,每次循环结束后都将其依次放到左边
比较的复杂度为O(N²)
交换的复杂度为O(N)
// 选择排序selectionSort() {const length = this.arr.length;for (let j = 0; j < length - 1; j++) {let min = j;for (let i = min + 1; i < length; i++) {if (this.arr[min] > this.arr[i]) {min = i;}}this.swap(min, j);}}
三、插入排序
插入排序的核心思想就是局部有序,比如左侧的一部分是有序的,右侧是无序的,那么就取无序的数据与有序数据比较,在合适的位置插入即可。
最坏:
比较的复杂度为O(N²)
移动的复杂度为O(N²)
// 插入排序insertionSort() {const length = this.arr.length;// 外层循环:从第1个位置开始获取数据,向前面的有序部分进行插入for (let i = 1; i < length; i++) {// 内层循环:获取i位置的元素,与前面的有序部分进行比较const temp = this.arr[i];let j = i;while (this.arr[j - 1] > temp && j > 0) {this.arr[j] = this.arr[j - 1];j--;}// 将j位置的数据,插入tempthis.arr[j] = temp;}}
