根据另一个数组的元素对数组进行排序 [英] Sort an array according to the elements of another array

查看:33
本文介绍了根据另一个数组的元素对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组 id

a1 = [1, 2, 3, 4, 5]  

我有另一个随机排列的 id 对象数组

and I have another array of objects with ids in random order

a2 = [(obj_with_id_5), (obj_with_id_2), (obj_with_id_1), (obj_with_id_3), (obj_with_id_4)]  

现在我需要根据a1中id的顺序对a2进行排序.所以 a2 现在应该变成:

Now I need to sort a2 according to the order of ids in a1. So a2 should now become:

[(obj_with_id_1), (id_2), (id_3), (id_4), (id_5)]  

a1 可能是 [3, 2, 5, 4, 1] 或任何顺序,但 a2 应该对应于 a1 中 id 的顺序.

a1 might be [3, 2, 5, 4, 1] or in any order but a2 should correspond to the order of ids in a1.

我喜欢这个:

a1.each_with_index do |id, idx|
  found_idx = a1.find_index { |c| c.id == id }
  replace_elem = a2[found_idx]
  a2[found_idx] = a2[idx]
  a2[idx] = replace_elem
end  

但是如果 a2 的元素顺序与 a1 完全相反,这仍然可能会遇到 O(n^2) 时间.有人可以告诉我排序 a2 的最有效方法吗?

But this still might run into an O(n^2) time if order of elements of a2 is exactly reverse of a1. Can someone please tell me the most efficient way of sorting a2?

推荐答案

hash_object = objects.each_with_object({}) do |obj, hash| 
  hash[obj.object_id] = obj
end

[1, 2, 3, 4, 5].map { |index| hash_object[index] }
#=> array of objects in id's order

我相信运行时间将是 O(n)

I believe that the run time will be O(n)

这篇关于根据另一个数组的元素对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆