I have an array of objects. the objects have a Boolean value in them that I want to use as a key for sorting the array (all objects with true come before all objects with false) but otherwise leave things in the same order.
我有一个对象数组。对象在其中有一个布尔值,我想用它作为一个键来排序数组(所有对象都是true,所有对象都在false之前),但在其他方面保留相同的顺序。
Is there a simple, in-place, O(n) solution to this? Maybe some variant of radix-sort?
有一个简单的,就地的O(n)解决方案吗?也许是基数排序的一些变种?
3 个解决方案
#1
See here for a discussion on this topic. You can basically have either an O(n)-solution which needs additional space or a O(n log n) in-place solution.
有关此主题的讨论,请参见此处。您基本上可以使用需要额外空间的O(n)解决方案或O(n log n)就地解决方案。
#2
Merge sort. O(n log n).
合并排序。 O(n log n)。
#3
Hmm. With a linked list it should be feasible - you'd search for the first "false" entry and keep it as the "insertion location". (If there are no "false" entries then you're done anyway :) Then just iterate through the whole list - if you're before the insertion location and find a "false" entry or if you're after the insertion location and find a "true" entry then move it to directly before the "insertion location". So far, so O(n)
.
嗯。使用链接列表它应该是可行的 - 您将搜索第一个“错误”条目并将其保留为“插入位置”。 (如果没有“假”条目,那么你无论如何都要完成:)然后只是遍历整个列表 - 如果你在插入位置之前找到一个“假”条目或者如果你在插入位置之后找到“真实”条目,然后将其移动到“插入位置”之前。到目前为止,所以O(n)。
Now you can convert an array into a linked list in O(n)
and you can copy the data back into the array in O(n)
. So I think it would work in terms of complexity - but it's not in-place. I'll think about whether it can be done in-place...
现在,您可以将数组转换为O(n)中的链接列表,并且可以将数据复制回O(n)中的数组。所以我认为它可以在复杂性方面起作用 - 但它不是原位的。我会考虑是否可以就地完成......
#1
See here for a discussion on this topic. You can basically have either an O(n)-solution which needs additional space or a O(n log n) in-place solution.
有关此主题的讨论,请参见此处。您基本上可以使用需要额外空间的O(n)解决方案或O(n log n)就地解决方案。
#2
Merge sort. O(n log n).
合并排序。 O(n log n)。
#3
Hmm. With a linked list it should be feasible - you'd search for the first "false" entry and keep it as the "insertion location". (If there are no "false" entries then you're done anyway :) Then just iterate through the whole list - if you're before the insertion location and find a "false" entry or if you're after the insertion location and find a "true" entry then move it to directly before the "insertion location". So far, so O(n)
.
嗯。使用链接列表它应该是可行的 - 您将搜索第一个“错误”条目并将其保留为“插入位置”。 (如果没有“假”条目,那么你无论如何都要完成:)然后只是遍历整个列表 - 如果你在插入位置之前找到一个“假”条目或者如果你在插入位置之后找到“真实”条目,然后将其移动到“插入位置”之前。到目前为止,所以O(n)。
Now you can convert an array into a linked list in O(n)
and you can copy the data back into the array in O(n)
. So I think it would work in terms of complexity - but it's not in-place. I'll think about whether it can be done in-place...
现在,您可以将数组转换为O(n)中的链接列表,并且可以将数据复制回O(n)中的数组。所以我认为它可以在复杂性方面起作用 - 但它不是原位的。我会考虑是否可以就地完成......