美文网首页Node.jsNode.js专题
js实现快速排序、归并排序

js实现快速排序、归并排序

作者: e042cbe4da21 | 来源:发表于2017-04-13 23:39 被阅读83次

    快速排序

    'use strict';
    
    const quickSort = function (array, low, high) {
      if (low >= high) {
        return;
      }
      let i = low;
      let j = high;
      const tmp = array[i];
      while (i < j) {
        while (i < j && array[j] >= tmp) {
          j--;
        }
        if (i < j) {
          array[i++] = array[j];
        }
        while (i < j && array[i] <= tmp) {
          i++;
        }
        if (i < j) {
          array[j--] = array[i];
        }
      }
      array[i] = tmp;
      quickSort(array, low, i - 1);
      quickSort(array, i + 1, high);
    }
    
    const arr = [1, 23, 7, 123, 45, 78, 10];
    console.log(arr);
    quickSort(arr, 0, arr.length - 1);
    console.log(arr);
    

    归并排序

    'use strict';
    
    // 两个有序数组合并
    const memeryArray = function (arr1, arr2) {
      const c = [];
      let i = 0;
      let j = 0;
      let k = 0;
      while (i < arr1.length && j < arr2.length) {
        if (arr1[i] < arr2[j]) c[k++] = arr1[i++];
        else c[k++] = arr2[j++];
      }
      while (i < arr1.length) c[k++] = arr1[i++];
      while (j < arr2.length) c[k++] = arr2[j++];
    
      return c;
    }
    
    // 将同一数组,两段有序序列合并
    const memery = function (arr, first, mid, last) {
      const temp = [];
      let i = first;
      const j = mid;
      let m = mid + 1;
      const n = last;
      let k = 0;
      while (i <= j && m <= n) {
        if (arr[i] < arr [m]) temp[k++] = arr[i++];
        else temp[k++] = arr[m++];
      }
      while (i <= j) temp[k++] = arr[i++];
      while (m <= n) temp[k++] = arr[m++];
      for (i = 0; i < k; i++) arr[first + i] = temp[i];
    }
    
    const mergeSort = function (arr, first, last) {
      if (!Array.isArray(arr)) throw new Error('argument is not a array');
      if (first < last) {
        const mid = parseInt((first + last) / 2, 10);
        mergeSort(arr, first, mid);
        mergeSort(arr, mid + 1, last);
        memery(arr, first, mid, last);
      }
    };
    
    const arr1 = [1, 7, 13, 20, 6, 9, 10, 10, 11, 26, 29];
    console.log(arr1);
    mergeSort(arr1, 0, arr1.length - 1);
    console.log(arr1);
    

    相关文章

      网友评论

        本文标题:js实现快速排序、归并排序

        本文链接:https://www.haomeiwen.com/subject/aviiattx.html