排序算法

coderljw 2024-10-13 算法
  • 排序算法
  • 算法
小于 1 分钟

# 1. 交换两数位置

const swap = (ary: any[], i: number, j: number) => {
  if (i === j) return
  const tep = ary[i]
  ary[i] = ary[j]
  ary[j] = tep
}
1
2
3
4
5
6

# 2. 选择排序

const selectSort = (ary?: number[]) => {
  if (!Array.isArray(ary) || ary.length < 2) return ary
  const len = ary.length
  for (let i = 0; i < len - 1; i++) {
    let minIndex = i
    for (let j = i + 1; j < len; j++) {
      if (ary[j] < ary[minIndex]) minIndex = j
    }
    swap(ary, i, minIndex)
  }
  return ary
}
1
2
3
4
5
6
7
8
9
10
11
12

# 3. 冒泡排序

const bubbleSort = (ary?: number[]) => {
  if (!Array.isArray(ary) || ary.length < 2) return ary
  const len = ary.length
  for (let end = len - 1; end > 0; end--) {
    for (let sec = 0; sec < end; sec++) {
      if (ary[sec] > ary[sec + 1]) swap(ary, sec, sec + 1)
    }
  }
  return ary
}

const bubbleSort = (ary?: number[]) => {
  if (!Array.isArray(ary) || ary.length < 2) return ary
  const len = ary.length
  for (let i = 0; i < len - 1; i++) {
    for (let j = 0; j < len - 1 - i; j++) {
      if (ary[j] > ary[j + 1]) swap(ary, j, j + 1)
    }
  }
  return ary
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 4. 插入排序

const insertSort = (ary?: number[]) => {
  if (!Array.isArray(ary) || ary.length < 2) return ary
  const len = ary.length
  for (let end = 1; end < len; end++) {
    for (let pre = end; pre > 0; pre--) {
      if (ary[pre - 1] > ary[pre]) swap(ary, pre - 1, pre)
    }
  }
  return ary
}

const insertSort = (ary?: number[]) => {
  if (!Array.isArray(ary) || ary.length < 2) return ary
  const len = ary.length
  for (let end = 1; end < len; end++) {
    let index = end
    while (index > 0 && ary[index - 1] > ary[index]) {
      swap(ary, index - 1, index)
      index--
    }
  }
  return ary
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
以父之名
周杰伦.mp3