js常用的几种排序方式

在JavaScript中,有多种排序方式可供选择。以下是几种常见的排序方式以及对应的示例:

  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]) {
            // 交换位置
            [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
          }
        }
      }
      return arr;
    }
    
    const nums = [5, 3, 8, 4, 2];
    const sortedNums = bubbleSort(nums); // [2, 3, 4, 5, 8]
    

  2. 插入排序(Insertion Sort): 插入排序的思想是将数组分为已排序和未排序两部分,每次从未排序部分取出一个元素插入到已排序部分的正确位置。

    function insertionSort(arr) {
      const len = arr.length;
      for (let i = 1; i < len; i++) {
        let current = arr[i];
        let j = i - 1;
        while (j >= 0 && arr[j] > current) {
          arr[j + 1] = arr[j];
          j--;
        }
        arr[j + 1] = current;
      }
      return arr;
    }
    
    const nums = [5, 3, 8, 4, 2];
    const sortedNums = insertionSort(nums); // [2, 3, 4, 5, 8]
    

  3. 选择排序(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) {
          [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]]; // 交换位置
        }
      }
      return arr;
    }
    
    const nums = [5, 3, 8, 4, 2];
    const sortedNums = selectionSort(nums); // [2, 3, 4, 5, 8]
    

  4. 快速排序(Quick Sort): 快速排序是一种常用的排序算法,它通过选择一个基准元素,将数组划分为左右两个子数组,然后递归地对子数组进行排序。

    function quickSort(arr) {
      if (arr.length <= 1) {
        return arr;
      }
      const pivotIndex = Math.floor(arr.length / 2);
      const pivot = arr.splice(pivotIndex, 1)[0];
      const left = [];
      const right = [];
      for (let i = 0; i < arr.length; i++) {
        if (arr[i] < pivot) {
          left.push(arr[i]);
        } else {
          right.push(arr[i]);
        }
      }
      return quickSort(left).concat([pivot], quickSort(right));
    }
    
    const nums = [5, 3, 8, 4, 2];
    const sortedNums = quickSort(nums); // [2, 3, 4, 5, 8]
    

    这些是几种常见的排序方式和对应的示例。值得注意的是,在实际应用中,可以根据排序需求和数据规模选择合适的排序算法。另外,JavaScript还提供了内置的排序函数Array.prototype.sort(),可以直接调用该函数对数组进行排序。

你可能感兴趣的:(javascript,开发语言,ecmascript)