虽然JavaScript本身给我们提供了sort排序方法,但是了解并掌握其它的排序算法能让你在面试中底气更足。话不多说,来看看这些算法是如何实现的吧!
1、冒泡排序
冒泡排序,就是两两比较相邻数字,如果左边的数字比右边的大,就左右交换,这样一轮循环下来最右边的数字即为最大值。然后下一次循环就可以忽略最后一项,因为最后一项已经是最大的了。下面来看看代码实现。
Array.prototype.bubbleSort = function () {
for (let i = 0; i < this.length - 1; i++) {
for (let j = 0; j < this.length - 1 - i; j++) {
const tmp = this[j];
this[j] = this[j + 1];
this[j + 1] = tmp;
}
}
return this;
}
let arr = [5, 4, 3, 2, 1];
console.log(arr.bubbleSort()); // [ 1, 2, 3, 4, 5 ]
可以明显看出,冒泡排序的时间复杂度为:O(n²)。
2、选择排序
所谓选择排序,就是先假设第一个数字为最小值,然后将其与后面的数字比较,如果后面的数字比他小,就把最小的数字更新为后面的数字,直至第一轮循环全部完成,并得到最小值,然后将最小值与第一个数字交换。下一轮循环就跳过第一个数字,因为它已经是最小的了。你看文字可能会感觉有点难懂,那就直接来看代码实现吧。
Array.prototype.selectionSort = function() {
for (let i = 0; i < this.length - 1; i++) {
let indexMin = i;
for (let j = i; j < this.length; j++) {
if (this[j] < this[indexMin]) {
indexMin = j;
}
}
if (indexMin !== i) {
const tmp = this[i];
this[i] = this[indexMin];
this[indexMin] = tmp;
}
}
return this;
}
let arr = [5, 4, 3, 2, 1];
console.log(arr.selectionSort()); // [ 1, 2, 3, 4, 5 ]
可以明显看出,选择排序的时间复杂度为:O(n²)。
3、插入排序
所谓插入排序,就是从数组中第二个数开始往前比,如果前面的数比第二个数大,则交换位置。至此第一轮结束。然后从第三个数开始,按之前的方法继续比较。直至数组排序完成。同样,来看代码实现。
Array.prototype.insertionSort = function() {
for (let i = 1 ; i < this.length; i++) {
const tmp = this[i];
let j = i;
while(j > 0) {
if (this[j - 1] > tmp) {
this[j] = this[j - 1];
} else {
break;
}
j--;
}
this[j] = tmp;
}
return this;
}
let arr = [5, 4, 3, 2, 1];
console.log(arr.insertionSort());
插入排序的时间复杂度也为:O(n²)。