【问题标题】:How to sort two sorted arrays without using sort methods (sort) nor sort algorithms (bubble sort, quick sort)如何在不使用排序方法(排序)或排序算法(冒泡排序、快速排序)的情况下对两个排序数组进行排序
【发布时间】:2023-03-19 16:20:02
【问题描述】:

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

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]
 }

【问题讨论】:

  • 你应该只是return output;
  • 循环结束后,arr1arr2 为空,无需合并到结果中。
  • 如果数组长度不等于@Barmar.
  • 但是 if 是多余的/错误的。删除它,它似乎是正确的?(未经测试)。
  • @YvesDaoust 因为它试图访问一个空数组的元素。

标签: javascript algorithm big-o


【解决方案1】:

您所说的——“排序”两个本身已经排序的数组——称为合并。你就是这样做的:

function merge( left = [] , right = [] )  {
  const merged = new Array( left.length + right.length );

  let i = 0 ;
  let j = 0 ;
  let k = 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[k++] = x;
      ++i;
    } else {
      merged[k++] = y;
      ++j;
    }

  }

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

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

  return merged;
}

【讨论】:

    【解决方案2】:

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

      // 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;
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2012-10-06
      • 1970-01-01
      • 2016-02-10
      • 1970-01-01
      • 2016-11-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-20
      • 1970-01-01
      相关资源
      最近更新 更多