js 几种常见的排序算法的实例

下面是几种常见的排序算法的实例:

1. 冒泡排序(Bubble Sort):

function bubbleSort(arr) {
  const len = arr.length;
  for (let i = 0; i < len - 1; i++) {
    for (let j = 0; j < len - 1 - i; j++) {
      if (arr[j] > arr[j + 1]) {
        let temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp;
      }
    }
  }
  return arr;
}

const arr = [64, 34, 25, 12, 22, 11, 90];
console.log(bubbleSort(arr)); // [11, 12, 22, 25, 34, 64, 90]

2. 选择排序(Selection Sort):

function selectionSort(arr) {
  const len = arr.length;
  for (let i = 0; i < len - 1; i++) {
    let minIndex = i;
    for (let j = i + 1; j < len; j++) {
      if (arr[j] < arr[minIndex]) {
        minIndex = j;
      }
    }
    if (minIndex !== i) {
      let temp = arr[i];
      arr[i] = arr[minIndex];
      arr[minIndex] = temp;
    }
  }
  return arr;
}

const arr = [64, 34, 25, 12, 22, 11, 90];
console.log(selectionSort(arr)); // [11, 12, 22, 25, 34, 64, 90]

3. 插入排序(Insertion Sort):

function insertionSort(arr) {
  const len = arr.length;
  for (let i = 1; i < len; i++) {
    let currentValue = arr[i];
    let j = i - 1;
    while (j >= 0 && arr[j] > currentValue) {
      arr[j + 1] = arr[j];
      j--;
    }
    arr[j + 1] = currentValue;
  }
  return arr;
}

const arr = [64, 34, 25, 12, 22, 11, 90];
console.log(insertionSort(arr)); // [11, 12, 22, 25, 34, 64, 90]

这些只是排序算法的一小部分实例。根据不同的需求和数据特点,选择合适的排序算法来提高效率和性能非常重要。

希望这些实例对你有帮助!如果还有其他问题,请随时提问。
 

猜你喜欢

转载自blog.csdn.net/weixin_39273589/article/details/132538757