1. 冒泡排序

时间复杂度O(n²)849589-20171015223238449-2146169197.gif

  1. Array.prototype.bubbleSort = function () {
  2. for (let i = 0; i < this.length; i++) {
  3. for (let j = 0; j < this.length - 1 - i; j++) {
  4. if (this[j] > this[j + 1]) {
  5. const temp = this[j];
  6. this[j] = this[j + 1];
  7. this[j + 1] = temp;
  8. }
  9. }
  10. }
  11. return this;
  12. };
  13. const arr = [5, 4, 3, 2, 1];
  14. console.log(arr.bubbleSort());

2. 选择排序

时间复杂度O(n²)
849589-20171015224719590-1433219824.gif

  1. Array.prototype.selectionSort = function () {
  2. for (let i = 0; i < this.length - 1; i++) {
  3. let minIndex = i;
  4. for (let j = i; j < this.length; j++) {
  5. if (this[j] < this[minIndex]) {
  6. minIndex = j;
  7. }
  8. }
  9. if (minIndex !== i) {
  10. const temp = this[i];
  11. this[i] = this[minIndex];
  12. this[minIndex] = temp;
  13. }
  14. }
  15. return this;
  16. };
  17. const arr = [5, 4, 3, 2, 1];
  18. console.log(arr.selectionSort());