JavaScript 各种排序算法实现

1. 冒泡

let arr = [1, 4, 5, 2, 3, 8, 11, 21, 6, 3, 12];
for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr.length - 1 - i; j++) {
        if (arr[j] > arr[j + 1]) {
            [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]
        }
    }
}

  

2. 选择排序

选择排序算法是一种原址比较排序算法。选择排序大致的思路是找到数据结构中的最小值并将其放置在第一位,接着找到第二小的值并将其放在第二位。

let arr = [1, 4, 5, 2, 3, 8, 11, 21, 6, 3, 12];
for (let index = 0; index < arr.length - 1; index++) {
    let min_index = index;
    for (let j = index; j < arr.length; j++) {
        if (arr[min_index] > arr[j]) {
            min_index = j;
        }
    }
    if (min_index !== index) {
        [arr[index], arr[min_index]] = [arr[min_index], arr[index]]
    }
}

3. 插入排序

猜你喜欢

转载自www.cnblogs.com/mykiya/p/11006708.html
今日推荐