文章结构
const swap = function(array, index1, index2) {
let arrCopy = array[index2];
array[index2] = array[index1];
array[index1] = arrCopy;
};
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]) {
swap(this, j, j + 1);
}
}
}
return this;
};
Array.prototype.selectionSort = function() {
for (let i = 0; i < this.length - 1; i++) {
let minIndex = i;
for (let j = i + 1; j < this.length; j++) {
if (this[minIndex] > this[j]) {
minIndex = j;
}
}
swap(this, i, minIndex);
}
return this;
};
Array.prototype.insertSort = function() {
let current = null;
let count;
for (let i = 1; i < this.length; i++) {
count = i;
current = this[count];
while (count > 0 && current < this[count - 1]) {
this[count] = this[count - 1];
count--;
}
this[count] = current;
}
return this;
};
Array.prototype.mergeSort = function() {
const mergeSortRec = function(array) {
if (array.length === 1) {
return array;
}
const mid = Math.floor(array.length / 2);
const left = array.slice(0, mid);
const right = array.slice(mid, array.length);
return merge(mergeSortRec(left), mergeSortRec(right));
};
const merge = function(left, right) {
let initLeft = 0;
let initRight = 0;
const result = [];
while (initLeft < left.length && initRight < right.length) {
if (left[initLeft] < right[initRight]) {
result.push(left[initLeft]);
initLeft++;
} else if (left[initLeft] > right[initRight]) {
result.push(right[initRight]);
initRight++;
} else {
result.push(left[initLeft]);
result.push(right[initRight]);
initLeft++;
initRight++;
}
}
if (initLeft !== left.length) {
for (let i = initLeft; i < left.length; i++) {
result.push(left[initLeft]);
initLeft++;
}
} else {
for (let i = initRight; i < right.length; i++) {
result.push(right[initRight]);
initRight++;
}
}
return result;
};
return mergeSortRec(this);
};
Array.prototype.quickSort = function() {
function quickSortRec(array) {
if (array.length === 1) {
return array;
}
const mid = array[Math.floor(array.length / 2)];
let leftIndex = 0;
let rightIndex = array.length - 1;
while (leftIndex < rightIndex) {
while (array[leftIndex] < mid && leftIndex < rightIndex) {
leftIndex++;
}
while (array[rightIndex] > mid && leftIndex < rightIndex) {
rightIndex--;
}
swap(array, leftIndex, rightIndex);
leftIndex++;
rightIndex--;
}
return quickSortRec(array.slice(0, Math.floor(array.length / 2))).concat(
quickSortRec(array.slice(Math.floor(array.length / 2), array.length))
);
}
return quickSortRec(this);
};