Home  >  Q&A  >  body text

Ruby 原地排序数组的一段

ruby 中想对数组中间的一段进行排序,我知道可以这样:

a[1..2] = a[1..2].sort!

但这样会有一次拷贝,出于效率原因希望不产生任何拷贝,直接在原数组上排序。

PHP中文网PHP中文网2759 days ago552

reply all(2)I'll reply

  • 怪我咯

    怪我咯2017-04-24 09:12:39

    Sort only copies the structure of the array, and the contents of the array will not be copied, so the impact on performance is minimal.

    What amount of data will make this code a performance bottleneck?

    reply
    0
  • 阿神

    阿神2017-04-24 09:12:39

    Using the sort method will regenerate a new array. You can use the array subscript to take out the elements for comparison, and just swap the positions

    reply
    0
  • Cancelreply