简体   繁体   English

美国国旗分类优化

[英]american flag sort optimization

I am trying to implement American Bucket Sort. 我正在尝试实施American Bucket Sort。 Wiki says "first to count the number of objects that will fall in each bin, and second to place each object in its bucket." Wiki说:“首先计算将落入每个容器中的对象数量,其次将每个对象放入其存储桶中。”

In second phase, when placing objects in proper buckets, Do I need to use auxiliary array? 在第二阶段,将对象放在适当的存储桶中时,是否需要使用辅助数组? Is there a way to do this by swapping array elements in linear time? 有没有办法通过在线性时间内交换数组元素来做到这一点?

Assuming you mean http://en.wikipedia.org/wiki/American_flag_sort , then as the article points out at the top, you can run this in-place (although then this is not a stable sort). 假设您的意思是http://en.wikipedia.org/wiki/American_flag_sort ,那么正如本文顶部指出的那样,您可以就地运行此代码(尽管这不是稳定的排序)。 The main idea is to have a pointer to the first item not read in, initially 0, and a temporary variable to hold one item. 主要思想是要有一个指向未读入的第一个项目的指针,最初是0,还有一个临时变量来保存一个项目。

As the first step you look at the pointer and pick up the item it points it. 第一步,您查看指针并拾取它指向的项目。 Now you can use the indexes to put it in place. 现在,您可以使用索引来放置它。 Unless its place is the position you originally read from, you are about to overwrite another item, so you swap the item you have picked up with the item you would overwrite, and you are now holding a different temporary item - and look up to see where it should go and carry on. 除非它的位置是您最初读取的位置,否则您将要覆盖另一个项目,因此您将要拾取的项目与要覆盖的项目交换,现在您持有另一个临时项目-抬头看一看应该去哪里继续下去。

Eventually you have put something into the place you read from, so you can increment the read pointer, skipping over areas where you have already written sorted items, pick up a different item, and carry on until everything is sorted. 最终,您将某些东西放到了要读取的位置,因此您可以增加读取指针,跳过已经写入已排序项目的区域,拾取另一个项目,然后继续进行直到所有内容都已排序为止。

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

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