冒泡排序(ts实现)
# 算法步骤
比较相邻的元素。如果第一个比第二个大,就交换他们两个。
对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。这步做完后,最后的元素会是最大的数。
针对所有的元素重复以上的步骤,除了最后一个。
持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。

# Code:
/***
 ** Created with WebStorm IDEA
 ** @Author: xinyu
 ** @Date: 2022/03/01/12:25
 ** @Description: 冒泡排序
 ***/*
import baseFunction = require("../utils/baseUtils");
let baseFunctions = new baseFunction()
let bubbleSort = (array,compareFn = baseFunctions.defaultCompare)=>{
  const {length} = array;
  for (let i = 0; i <length ; i++) {
    for (let j = 0; j <length-1 ; j++) {
      if (compareFn.call(baseFunctions,array[j],array[j+1])===baseFunctions.Compare.BIGGER_THAN)
        baseFunctions.swap(array,j,j+1)
    }
  }
  return array
}
console.log(bubbleSort(baseFunctions.testArray));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 优化:
*/**
 ** Created with WebStorm IDEA.*
 ** @Author: xinyu
 ** @Date: 2022/03/01/19:17
 ** @Description: 冒泡排序的优化
 **/*
import baseFunction = require("../utils/baseUtils");
let baseFunctions = new baseFunction()
let modifedBubbleSort=(array,compareFn=baseFunctions.defaultCompare)=>{
  const {length} = array;
  for (let i = 0; i <length ; i++) {
    for (let j = 0; j <length-1-i ; j++) {
      if (compareFn(array[j],array[j+1])===1)
        baseFunctions.swap(array,j,j+1);
    }
  }
  return array
}
console.log(modifedBubbleSort(baseFunctions.testArray));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
上次更新: 2023/09/05 17:45:42
