繁体   English   中英

如何在不使用排序方法(排序)或排序算法(冒泡排序、快速排序)的情况下对两个已排序的 arrays 进行排序

[英]How to sort two sorted arrays without using sort methods (sort) nor sort algorithms (bubble sort, quick sort)

我在一次采访中被问到,我的回答与此类似,由于最终循环,这是错误的。

 const newSortArrays = (arr1, arr2) => { let output = []; while (arr1.length && arr2.length) { if (arr1[0] < arr2[0]) output.push(arr1[0] < arr2[0]? arr1.shift(): arr2.shift()) } return [...output, ...arr1, ...arr2] }

你在说什么 - “排序”两个 arrays 本身已经排序称为合并 这就是你这样做的方式:

function merge( left = [] , right = [] )  {
  const merged = [];

  let i = 0 ;
  let j = 0 ;

  // while both lists have items
  while ( i < left.length && j < right.length ) {
    const x = left[i];
    const y = right[j];

    if ( x <= y ) {
      merged.push(x);
      ++i;
    } else {
      merged.push(y);
      ++j;
    }

  }

  // if the left list still has items, take them
  while ( i < left.length ) {
    merged.push( left[ i++ ] );
  }

  // if the right list still has items, take them
  while ( j < right.length ) {
    merged.push( right[ j++ ] );
  }

  return merged;
}

一个(效率较低的)单循环变体:

  // While some list is not empty
  while ( i < left.length || j < right.length ) {
    if ( i < left.length && ( j >= right.length || left[i] < right[j] ) ) {
      merged[k++] = left[i];
      ++i;
    } else {
      merged[k++] = right[j];
      ++j;
    }
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM